form-data vs busboy vs formidable vs multer vs express-fileupload vs koa-body vs connect-busboy
Node.js File Upload Libraries Comparison
1 Year
form-databusboyformidablemulterexpress-fileuploadkoa-bodyconnect-busboySimilar Packages:
What's Node.js File Upload Libraries?

These libraries facilitate file uploads in Node.js applications, providing various methods to handle multipart/form-data. They differ in terms of middleware integration, performance, and feature sets, catering to different use cases and frameworks such as Express and Koa. Understanding their unique functionalities helps developers choose the right tool for their specific needs.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
form-data89,334,7082,30431.8 kB13417 days agoMIT
busboy16,083,7702,901124 kB36--
formidable10,887,2267,105203 kB504 months agoMIT
multer6,561,60211,71227.6 kB269-MIT
express-fileupload374,1451,542116 kB238 months agoMIT
koa-body343,01895038.2 kB52-MIT
connect-busboy46,2551554.57 kB0--
Feature Comparison: form-data vs busboy vs formidable vs multer vs express-fileupload vs koa-body vs connect-busboy

Integration

  • form-data:

    Form-Data is primarily used for constructing multipart/form-data requests, making it suitable for client-side applications rather than server-side file handling.

  • busboy:

    Busboy is a low-level streaming parser that requires manual integration into your application, giving you full control over the file upload process but requiring more setup.

  • formidable:

    Formidable can be used with any Node.js application, providing a comprehensive solution for file uploads and form parsing, but it requires more setup than simpler libraries.

  • multer:

    Multer is a middleware for Express that simplifies file uploads, providing built-in support for various storage options and configuration.

  • express-fileupload:

    Express-Fileupload is designed specifically for Express, providing a plug-and-play solution for file uploads with minimal configuration needed.

  • koa-body:

    Koa-Body integrates seamlessly with Koa, allowing for easy handling of multipart/form-data in Koa applications, with a straightforward API.

  • connect-busboy:

    Connect-Busboy integrates Busboy with Connect middleware, simplifying the process of handling file uploads in Connect-based applications.

Performance

  • form-data:

    Form-Data is optimized for creating requests but is not designed for handling uploads on the server side, so performance considerations depend on the use case.

  • busboy:

    Busboy is highly efficient for large file uploads due to its streaming nature, which minimizes memory usage and allows for processing files in chunks.

  • formidable:

    Formidable is efficient for file uploads but can consume more memory than Busboy, especially with large files, as it buffers uploads before processing.

  • multer:

    Multer provides excellent performance for file uploads in Express applications, with options to store files in memory or on disk, allowing for flexible handling.

  • express-fileupload:

    Express-Fileupload is easy to use but may not be as performant as Busboy for very large files, as it buffers the entire file in memory before processing.

  • koa-body:

    Koa-Body is designed for Koa applications and offers good performance, but like Express-Fileupload, it may buffer files in memory depending on configuration.

  • connect-busboy:

    Performance is similar to Busboy, as it utilizes the same underlying library, but may introduce slight overhead due to middleware integration.

Ease of Use

  • form-data:

    Form-Data is easy to use for constructing requests but is not focused on server-side file handling, which may require additional libraries for uploads.

  • busboy:

    Busboy requires more manual setup and configuration, making it less beginner-friendly but offering greater control for experienced developers.

  • formidable:

    Formidable has a moderate learning curve, offering comprehensive functionality but requiring more understanding of its API and options.

  • multer:

    Multer is designed to be easy to use with Express, allowing developers to quickly set up file uploads with clear configuration options.

  • express-fileupload:

    Express-Fileupload is very easy to use, with minimal setup required, making it ideal for beginners or quick prototypes.

  • koa-body:

    Koa-Body is user-friendly for Koa applications, providing a clean API for handling file uploads and form data with minimal configuration.

  • connect-busboy:

    Connect-Busboy is straightforward to use within Connect applications, providing a simple API for file uploads without much boilerplate code.

File Handling Features

  • form-data:

    Form-Data focuses on creating multipart requests and does not handle file uploads on the server side, requiring additional handling for uploads.

  • busboy:

    Busboy allows for streaming file uploads, enabling developers to process files as they are being uploaded, which is useful for large files.

  • formidable:

    Formidable offers robust file handling features, including file renaming, size limits, and error handling, making it suitable for complex applications.

  • multer:

    Multer provides extensive file handling features, including storage options, file size limits, and file filtering, making it highly configurable for various use cases.

  • express-fileupload:

    Express-Fileupload provides simple file handling features but lacks advanced options for file processing compared to other libraries.

  • koa-body:

    Koa-Body supports file uploads and provides a clean API for accessing uploaded files, making it easy to work with in Koa applications.

  • connect-busboy:

    Connect-Busboy inherits Busboy's file handling capabilities, allowing for streaming uploads within Connect applications.

Community and Support

  • form-data:

    Form-Data is widely used for constructing requests and has good community support, but it is not focused on server-side uploads.

  • busboy:

    Busboy has a smaller community compared to some other libraries, but it is well-maintained and widely used in production applications.

  • formidable:

    Formidable has been around for a while and has a solid community, providing ample resources and support for developers.

  • multer:

    Multer has a large community and is widely adopted in Express applications, ensuring good support and documentation.

  • express-fileupload:

    Express-Fileupload has a large user base and community support, making it easy to find help and resources online.

  • koa-body:

    Koa-Body is part of the Koa ecosystem, which has a growing community and support for Koa-related libraries.

  • connect-busboy:

    Connect-Busboy benefits from the Connect community, which provides support and resources for users.

How to Choose: form-data vs busboy vs formidable vs multer vs express-fileupload vs koa-body vs connect-busboy
  • form-data:

    Opt for Form-Data when you need to construct and send multipart/form-data requests from Node.js. It is particularly useful for client-side applications that require file uploads to a server.

  • busboy:

    Choose Busboy for a lightweight, low-level streaming parser that is efficient for handling large file uploads without additional overhead. It is ideal for applications that require fine-grained control over file processing.

  • formidable:

    Choose Formidable for a robust file upload solution that supports file uploads and form parsing. It is well-suited for applications that require detailed file handling and form data processing.

  • multer:

    Use Multer when working with Express and need a powerful middleware for handling multipart/form-data. It offers extensive configuration options for file storage and limits, making it ideal for complex file upload scenarios.

  • express-fileupload:

    Use Express-Fileupload for an easy-to-use solution that integrates directly with Express. It simplifies file upload handling with minimal setup, making it suitable for quick projects or prototypes.

  • koa-body:

    Select Koa-Body if you are building applications with Koa and need a middleware that supports multipart/form-data. It provides a clean API for handling file uploads and form data in Koa applications.

  • connect-busboy:

    Select Connect-Busboy if you are using Connect middleware and need a simple way to integrate Busboy with your existing Connect-based application. It offers a straightforward approach to handle file uploads seamlessly within Connect.

README for form-data

Form-Data NPM Module Join the chat at https://gitter.im/form-data/form-data

A library to create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.

The API of this library is inspired by the XMLHttpRequest-2 FormData Interface.

Linux Build MacOS Build Windows Build

Coverage Status Dependency Status

Install

npm install --save form-data

Usage

In this example we are constructing a form with 3 fields that contain a string, a buffer and a file stream.

var FormData = require('form-data');
var fs = require('fs');

var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

Also you can use http-response stream:

var FormData = require('form-data');
var http = require('http');

var form = new FormData();

http.request('http://nodejs.org/images/logo.png', function(response) {
  form.append('my_field', 'my value');
  form.append('my_buffer', new Buffer(10));
  form.append('my_logo', response);
});

Or @mikeal's request stream:

var FormData = require('form-data');
var request = require('request');

var form = new FormData();

form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', request('http://nodejs.org/images/logo.png'));

In order to submit this form to a web application, call submit(url, [callback]) method:

form.submit('http://example.org/', function(err, res) {
  // res – response object (http.IncomingMessage)  //
  res.resume();
});

For more advanced request manipulations submit() method returns http.ClientRequest object, or you can choose from one of the alternative submission methods.

Custom options

You can provide custom options, such as maxDataSize:

var FormData = require('form-data');

var form = new FormData({ maxDataSize: 20971520 });
form.append('my_field', 'my value');
form.append('my_buffer', /* something big */);

List of available options could be found in combined-stream

Alternative submission methods

You can use node's http client interface:

var http = require('http');

var request = http.request({
  method: 'post',
  host: 'example.org',
  path: '/upload',
  headers: form.getHeaders()
});

form.pipe(request);

request.on('response', function(res) {
  console.log(res.statusCode);
});

Or if you would prefer the 'Content-Length' header to be set for you:

form.submit('example.org/upload', function(err, res) {
  console.log(res.statusCode);
});

To use custom headers and pre-known length in parts:

var CRLF = '\r\n';
var form = new FormData();

var options = {
  header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
  knownLength: 1
};

form.append('my_buffer', buffer, options);

form.submit('http://example.com/', function(err, res) {
  if (err) throw err;
  console.log('Done');
});

Form-Data can recognize and fetch all the required information from common types of streams (fs.readStream, http.response and mikeal's request), for some other types of streams you'd need to provide "file"-related information manually:

someModule.stream(function(err, stdout, stderr) {
  if (err) throw err;

  var form = new FormData();

  form.append('file', stdout, {
    filename: 'unicycle.jpg', // ... or:
    filepath: 'photos/toys/unicycle.jpg',
    contentType: 'image/jpeg',
    knownLength: 19806
  });

  form.submit('http://example.com/', function(err, res) {
    if (err) throw err;
    console.log('Done');
  });
});

The filepath property overrides filename and may contain a relative path. This is typically used when uploading multiple files from a directory.

For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to form.submit() as first parameter:

form.submit({
  host: 'example.com',
  path: '/probably.php?extra=params',
  auth: 'username:password'
}, function(err, res) {
  console.log(res.statusCode);
});

In case you need to also send custom HTTP headers with the POST request, you can use the headers key in first parameter of form.submit():

form.submit({
  host: 'example.com',
  path: '/surelynot.php',
  headers: {'x-test-header': 'test-header-value'}
}, function(err, res) {
  console.log(res.statusCode);
});

Methods

Void append( String field, Mixed value [, Mixed options] )

Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user.

var form = new FormData();
form.append( 'my_string', 'my value' );
form.append( 'my_integer', 1 );
form.append( 'my_boolean', true );
form.append( 'my_buffer', new Buffer(10) );
form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )

You may provide a string for options, or an object.

// Set filename by providing a string for options
form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );

// provide an object.
form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );

Headers getHeaders( [Headers userHeaders] )

This method adds the correct content-type header to the provided array of userHeaders.

String getBoundary()

Return the boundary of the formData. By default, the boundary consists of 26 - followed by 24 numbers for example:

--------------------------515890814546601021194782

Void setBoundary(String boundary)

Set the boundary string, overriding the default behavior described above.

Note: The boundary must be unique and may not appear in the data.

Buffer getBuffer()

Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.

var form = new FormData();
form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) );
form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );

axios.post( 'https://example.com/path/to/api',
            form.getBuffer(),
            form.getHeaders()
          )

Note: Because the output is of type Buffer, you can only append types that are accepted by Buffer: string, Buffer, ArrayBuffer, Array, or Array-like Object. A ReadStream for example will result in an error.

Integer getLengthSync()

Same as getLength but synchronous.

Note: getLengthSync doesn't calculate streams length.

Integer getLength( function callback )

Returns the Content-Length async. The callback is used to handle errors and continue once the length has been calculated

this.getLength(function(err, length) {
  if (err) {
    this._error(err);
    return;
  }

  // add content length
  request.setHeader('Content-Length', length);

  ...
}.bind(this));

Boolean hasKnownLength()

Checks if the length of added values is known.

Request submit( params, function callback )

Submit the form to a web application.

var form = new FormData();
form.append( 'my_string', 'Hello World' );

form.submit( 'http://example.com/', function(err, res) {
  // res – response object (http.IncomingMessage)  //
  res.resume();
} );

String toString()

Returns the form data as a string. Don't use this if you are sending files or buffers, use getBuffer() instead.

Integration with other libraries

Request

Form submission using request:

var formData = {
  my_field: 'my_value',
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};

request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});

For more details see request readme.

node-fetch

You can also submit a form using node-fetch:

var form = new FormData();

form.append('a', 1);

fetch('http://example.com', { method: 'POST', body: form })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

axios

In Node.js you can post a file using axios:

const form = new FormData();
const stream = fs.createReadStream(PATH_TO_FILE);

form.append('image', stream);

// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();

axios.post('http://example.com', form, {
  headers: {
    ...formHeaders,
  },
})
.then(response => response)
.catch(error => error)

Notes

  • getLengthSync() method DOESN'T calculate length for streams, use knownLength options as workaround.
  • getLength(cb) will send an error as first parameter of callback if stream length cannot be calculated (e.g. send in custom streams w/o using knownLength).
  • submit will not add content-length if form length is unknown or not calculable.
  • Starting version 2.x FormData has dropped support for node@0.10.x.
  • Starting version 3.x FormData has dropped support for node@4.x.

License

Form-Data is released under the MIT license.