Coder Social home page Coder Social logo

quicksend / transmit Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 0.0 13.47 MB

An alternative to Multer for handling multipart/form-data

Home Page: https://quicksend.github.io/transmit

License: MIT License

JavaScript 0.45% TypeScript 99.55%
multipart form-data file-upload form formdata nodejs javascript typescript

transmit's Introduction

Transmit

Build Status Coverage Status

An alternative to Multer for handling multipart/form-data

Why?

Multer and many other multipart/form-data parsers don't remove uploaded files if the request is aborted. This can be a problem if a user uploads large files and abruptly aborts the request, leaving the partially uploaded (and potentially large) file on your system. Transmit automatically deletes uploaded files if it detects that the request has been aborted.

In addition, Transmit offers a modern API, making use of promises. It also allows you to process and transform incoming files with the use of transformer functions.

Prerequisites

Installation

$ npm install @quicksend/transmit
$ npm install -D @types/busboy

Usage

By default, all files are saved within the os.tmpdir() folder. You can change this by specifying the directory in the options of DiskManager.

Example with Express using a custom upload destination:

const { DiskManager, Transmit } = require("@quicksend/transmit");

const express = require("express");

const app = express();

// Implement transmit as an express middleware
const upload = (options = {}) => (req, _res, next) => {
  return new Transmit(options)
    .parseAsync(req)
    .then((results) => {
      req.fields = results.fields;
      req.files = results.files;

      next();
    })
    .catch((error) => next(error));
};

const manager = new DiskManager({
  directory: "./uploads"
});

app.post("/upload", upload({ manager }), (req, res) => {
  res.send({
    fields: req.fields,
    files: req.files
  });
});

app.listen(3000, () => {
  console.log("Listening on port 3000");
});

Example with Node.js http module:

const { Transmit } = require("@quicksend/transmit");

const http = require("http");

const server = http.createServer(async (req, res) => {
  if (req.url !== "/upload" || req.method.toLowerCase() !== "post") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "Not Found." }));

    return;
  }

  try {
    const results = await new Transmit().parseAsync(req);

    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(results, null, 2));
  } catch (error) {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(error));
  }
});

server.listen(3000, () => {
  console.log("Listening on port 3000");
});

NestJS

Transmit can be used with NestJS. Install nestjs-transmit and follow the instructions on the README.

$ npm install @quicksend/nestjs-transmit

Transformers

Files can be transformed before it is written to the storage medium. A use case would be resizing uploaded images.

A transformer must be a function that returns a readable stream.

Transformers will run sequentially in the order that they were placed.

Example with sharp as a resize transformer:

const { DiskManager, Transmit } = require("@quicksend/transmit");

const express = require("express");
const sharp = require("sharp");

const app = express();

// Implement transmit as an express middleware
const upload = (options = {}) => (req, _res, next) => {
  return new Transmit(options)
    .parseAsync(req)
    .then((results) => {
      req.fields = results.fields;
      req.files = results.files;

      next();
    })
    .catch((error) => next(error));
};

const manager = new DiskManager({
  directory: "./uploads"
});

app.post(
  "/upload",
  upload({
    filter: (file) => /^image/.test(file.mimetype), // ignore any files that are not images
    manager,
    transformers: [() => sharp().resize(128, 128).png()], // resize any incoming image to 128x128 and save it as a png
  }),
  (req, res) => {
    res.send({
      fields: req.fields,
      files: req.files
    });
  }
);

app.listen(3000, () => {
  console.log("Listening on port 3000");
});

Custom transmit managers

You can create your own transmit managers. All managers must implement the TransmitManager interface.

import { IncomingFile, TransmitManager } from "@quicksend/transmit";

export class CustomTransmitManager implements TransmitManager {
  handleFile(file: IncomingFile): Promise<NodeJS.WritableStream> | NodeJS.WritableStream {}
  removeFile(file: IncomingFile): Promise<void> | void {}
}

Documentation

Detailed documentation can be found here

You can build the documentation by running:

$ npm run docs

Tests

Run tests using the following commands:

$ npm run test
$ npm run test:watch # run jest in watch mode during development

Generate coverage reports by running:

$ npm run coverage

transmit's People

Contributors

alexy4744 avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

transmit's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.