form-data vs formidable vs multer vs express-fileupload vs koa-body vs connect-busboy vs busboy
ファイルアップロードライブラリ
form-dataformidablemulterexpress-fileuploadkoa-bodyconnect-busboybusboy類似パッケージ:

ファイルアップロードライブラリ

ファイルアップロードライブラリは、Node.jsアプリケーションにおいて、クライアントからサーバーへのファイル転送を簡素化するためのツールです。これらのライブラリは、HTTPリクエストの処理、ファイルのストリーミング、メモリ管理、エラーハンドリングなどの機能を提供し、開発者がファイルアップロード機能を迅速に実装できるようにします。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
form-data124,708,0862,35681.2 kB1364ヶ月前MIT
formidable15,493,557-204 kB-1年前MIT
multer11,159,41812,01831.5 kB2478日前MIT
express-fileupload393,1891,562119 kB248ヶ月前MIT
koa-body358,63595360.7 kB373ヶ月前MIT
connect-busboy28,7891564.57 kB0--
busboy02,996124 kB37--

機能比較: form-data vs formidable vs multer vs express-fileupload vs koa-body vs connect-busboy vs busboy

ストリーミング処理

  • form-data:

    Form-dataは、ストリーミング処理を提供しませんが、リクエストのデータを簡単に構築できます。

  • formidable:

    Formidableは、ストリーミング処理をサポートしており、大きなファイルを効率的に処理できます。

  • multer:

    Multerは、ストリーミング処理を行わず、メモリまたはディスクにファイルを保存するためのオプションを提供します。

  • express-fileupload:

    Express-fileuploadは、ストリーミング処理をサポートしていないため、大きなファイルのアップロードには不向きです。

  • koa-body:

    Koa-bodyは、Koaフレームワークにおいてストリーミング処理をサポートし、ファイルアップロードを効率的に行います。

  • connect-busboy:

    Connect-busboyもストリーミングをサポートしますが、Busboyのラッパーとして機能し、Expressアプリケーションに統合しやすいです。

  • busboy:

    Busboyは、ストリーミングAPIを使用してファイルを処理し、大きなファイルのアップロードを効率的に行います。

エラーハンドリング

  • form-data:

    Form-dataは、エラーハンドリングの機能を持たず、主にデータ構築に焦点を当てています。

  • formidable:

    Formidableは、詳細なエラーハンドリング機能を提供し、ファイルの解析中に発生したエラーを適切に処理できます。

  • multer:

    Multerは、エラーハンドリングをサポートしており、ファイルサイズやタイプの制限に関するエラーを処理できます。

  • express-fileupload:

    Express-fileuploadは、シンプルなエラーハンドリングを提供しますが、詳細なエラー情報は提供されません。

  • koa-body:

    Koa-bodyは、Koaのエラーハンドリング機能を活用し、エラーを適切に処理できます。

  • connect-busboy:

    Connect-busboyもエラーハンドリングをサポートしており、エラーをミドルウェアで処理できます。

  • busboy:

    Busboyは、エラーが発生した場合にイベントを発火させ、開発者が適切に処理できるようにします。

使いやすさ

  • form-data:

    Form-dataは、HTTPリクエストのデータを構築するための便利な機能を提供しますが、ファイルアップロード専用ではありません。

  • formidable:

    Formidableは、強力な機能を持っていますが、設定が複雑な場合があります。

  • multer:

    Multerは、設定が簡単で、特にExpressアプリケーションでの使用に適しています。

  • express-fileupload:

    Express-fileuploadは、シンプルなAPIを提供しており、迅速に導入できます。

  • koa-body:

    Koa-bodyは、Koaフレームワークに特化しており、使いやすさが高いです。

  • connect-busboy:

    Connect-busboyは、Expressアプリケーションに簡単に統合できるため、使いやすさが向上します。

  • busboy:

    Busboyは、ストリーミングAPIを使用するため、使い方に慣れるまでに時間がかかる場合があります。

ファイルサイズの制限

  • form-data:

    Form-dataは、ファイルサイズの制限を設定する機能を持ちません。

  • formidable:

    Formidableは、ファイルサイズの制限を設定する機能を提供し、大きなファイルのアップロードを制御できます。

  • multer:

    Multerは、ファイルサイズの制限を簡単に設定でき、特にExpressアプリケーションでの使用に適しています。

  • express-fileupload:

    Express-fileuploadは、ファイルサイズの制限を簡単に設定できるため、大きなファイルのアップロードを制御できます。

  • koa-body:

    Koa-bodyは、ファイルサイズの制限を設定するオプションを提供します。

  • connect-busboy:

    Connect-busboyも同様に、ファイルサイズの制限を設定する機能がありません。

  • busboy:

    Busboyは、ファイルサイズの制限を設定する機能を持たず、開発者が手動で管理する必要があります。

ストレージオプション

  • form-data:

    Form-dataは、ストレージオプションを持たず、データ構築に特化しています。

  • formidable:

    Formidableは、ファイルをディスクに保存するための柔軟なストレージオプションを提供します。

  • multer:

    Multerは、メモリまたはディスクにファイルを保存するための柔軟なストレージオプションを提供します。

  • express-fileupload:

    Express-fileuploadは、メモリにファイルを保存するオプションを提供しますが、ストレージオプションは限られています。

  • koa-body:

    Koa-bodyは、ストレージオプションを持たず、ファイルの保存方法は開発者が管理する必要があります。

  • connect-busboy:

    Connect-busboyもストレージオプションを提供しません。

  • busboy:

    Busboyは、ストレージオプションを提供せず、ファイルの保存方法は開発者が管理する必要があります。

選び方: form-data vs formidable vs multer vs express-fileupload vs koa-body vs connect-busboy vs busboy

  • form-data:

    Form-dataは、HTTPリクエストのデータを簡単に構築するためのライブラリで、ファイルアップロードだけでなく、他のデータも送信する必要がある場合に適しています。

  • formidable:

    Formidableは、ファイルのアップロードと解析を行うための強力なライブラリで、複雑なフォームデータを扱う必要がある場合に最適です。

  • multer:

    Multerは、Expressのミドルウェアとして非常に人気があり、ファイルのストレージオプションを柔軟に設定できるため、特にExpressアプリケーションでの使用に適しています。

  • express-fileupload:

    Express-fileuploadは、シンプルなAPIを提供し、迅速にファイルアップロード機能を追加したい場合に便利です。

  • koa-body:

    Koa-bodyは、Koaフレームワーク用のミドルウェアで、Koaを使用している場合にファイルアップロードを簡単に処理できます。

  • connect-busboy:

    Connect-busboyは、ConnectやExpressのミドルウェアとして使用され、既存のアプリケーションに簡単に統合できるため、Expressを使用している場合に適しています。

  • busboy:

    Busboyは、ストリーミングAPIを提供し、大きなファイルを効率的に処理する必要がある場合に最適です。

form-data のREADME

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.