busboy vs formidable vs multer vs express-fileupload vs connect-busboy vs connect-multiparty
ファイルアップロードライブラリ
busboyformidablemulterexpress-fileuploadconnect-busboyconnect-multiparty類似パッケージ:
ファイルアップロードライブラリ

ファイルアップロードライブラリは、Node.jsアプリケーションがHTTPリクエストを介してサーバーにファイルをアップロードするのを処理するためのツールです。これらのライブラリは、マルチパートフォームデータを解析し、アップロードされたファイルをストリームとして処理したり、一時的なストレージに保存したりします。これにより、ウェブアプリケーションはユーザーからのファイル入力を受け取り、データベースに保存したり、クラウドストレージにアップロードしたり、他の処理を行ったりすることができます。

npmのダウンロードトレンド
3 年
GitHub Starsランキング
統計詳細
パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
busboy19,320,2542,978124 kB37--
formidable15,240,990-204 kB-8ヶ月前MIT
multer9,704,01411,95729.5 kB2465ヶ月前MIT
express-fileupload438,4581,558119 kB235ヶ月前MIT
connect-busboy48,3201564.57 kB0--
connect-multiparty48,164349-07年前MIT
機能比較: busboy vs formidable vs multer vs express-fileupload vs connect-busboy vs connect-multiparty

ストリーミング処理

  • busboy:

    busboyは、ファイルをストリームとして処理するため、メモリ使用量を最小限に抑えながら大きなファイルを効率的にアップロードできます。

  • formidable:

    formidableは、ファイルをストリームとして処理し、アップロード中にリアルタイムでデータを処理できます。

  • multer:

    multerは、ファイルをストリーミングで処理しますが、アップロード前に一時的にメモリまたはディスクに保存します。

  • express-fileupload:

    express-fileuploadは、ストリーミング処理をサポートしていません。ファイルは一時的にメモリまたはディスクに保存されます。

  • connect-busboy:

    connect-busboyは、busboyのストリーミング機能を活用し、ファイルをリアルタイムで処理できます。

  • connect-multiparty:

    connect-multipartyは、ストリーミング処理をサポートしていません。ファイルは一時的に保存されてから処理されます。

ファイルサイズ制限

  • busboy:

    busboyは、ファイルサイズ制限を手動で実装する必要があります。

  • formidable:

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

  • multer:

    multerは、ファイルサイズ制限を設定するためのシンプルなAPIを提供します。

  • express-fileupload:

    express-fileuploadは、ファイルサイズ制限を簡単に設定できるオプションを提供します。

  • connect-busboy:

    connect-busboyも同様に、ファイルサイズ制限は手動で設定する必要があります。

  • connect-multiparty:

    connect-multipartyは、ファイルサイズ制限を設定できますが、ドキュメントは限られています。

カスタムストレージ

  • busboy:

    busboyは、カスタムストレージロジックを実装するための柔軟性がありますが、組み込みのストレージ機能はありません。

  • formidable:

    formidableは、カスタムストレージロジックを実装するための柔軟性があります。

  • multer:

    multerは、カスタムストレージロジックを簡単に実装できるインターフェースを提供します。

  • express-fileupload:

    express-fileuploadは、カスタムストレージロジックを実装するためのフックを提供しますが、デフォルトでは一時的なストレージを使用します。

  • connect-busboy:

    connect-busboyは、busboyと同様に、カスタムストレージロジックを実装する必要があります。

  • connect-multiparty:

    connect-multipartyは、ファイルを一時的なディレクトリに保存しますが、カスタムストレージロジックは提供されていません。

使いやすさ

  • busboy:

    busboyは、ストリーミングAPIを提供しますが、使い方には慣れが必要です。

  • formidable:

    formidableは、強力な機能を提供しますが、使い方には少し学習が必要です。

  • multer:

    multerは、シンプルなAPIを提供し、使いやすさと柔軟性のバランスが取れています。

  • express-fileupload:

    express-fileuploadは、シンプルで直感的なAPIを提供し、設定が簡単です。

  • connect-busboy:

    connect-busboyは、busboyExpressアプリケーションに簡単に統合できます。

  • connect-multiparty:

    connect-multipartyは、シンプルなAPIを提供し、使いやすいですが、ドキュメントは限られています。

コード例

  • busboy:

    busboyを使用したファイルアップロードの例

    const Busboy = require('busboy');
    const fs = require('fs');
    const express = require('express');
    const app = express();
    
    app.post('/upload', (req, res) => {
      const busboy = new Busboy({ headers: req.headers });
      busboy.on('file', (fieldname, file, filename) => {
        const writeStream = fs.createWriteStream(`./uploads/${filename}`);
        file.pipe(writeStream);
      });
      busboy.on('finish', () => {
        res.send('ファイルアップロード完了');
      });
      req.pipe(busboy);
    });
    
    app.listen(3000, () => {
      console.log('サーバーがポート3000で起動');
    });
    
  • formidable:

    formidableを使用したファイルアップロードの例

    const express = require('express');
    const formidable = require('formidable');
    const fs = require('fs');
    const app = express();
    
    app.post('/upload', (req, res) => {
      const form = new formidable.IncomingForm();
      form.uploadDir = './uploads';
      form.on('fileBegin', (name, file) => {
        file.path = `${form.uploadDir}/${file.name}`;
      });
      form.on('end', () => {
        res.send('ファイルアップロード完了');
      });
      form.parse(req);
    });
    
    app.listen(3000, () => {
      console.log('サーバーがポート3000で起動');
    });
    
  • multer:

    multerを使用したファイルアップロードの例

    const express = require('express');
    const multer = require('multer');
    const fs = require('fs');
    const app = express();
    
    const storage = multer.diskStorage({
      destination: (req, file, cb) => {
        cb(null, './uploads');
      },
      filename: (req, file, cb) => {
        cb(null, file.originalname);
      }
    });
    const upload = multer({ storage });
    
    app.post('/upload', upload.single('file'), (req, res) => {
      res.send('ファイルアップロード完了');
    });
    
    app.listen(3000, () => {
      console.log('サーバーがポート3000で起動');
    });
    
  • express-fileupload:

    express-fileuploadを使用したファイルアップロードの例

    const express = require('express');
    const fileUpload = require('express-fileupload');
    const fs = require('fs');
    const app = express();
    
    app.use(fileUpload());
    
    app.post('/upload', (req, res) => {
      const file = req.files.file;
      const uploadPath = `./uploads/${file.name}`;
      file.mv(uploadPath, err => {
        if (err) return res.status(500).send(err);
        res.send('ファイルアップロード完了');
      });
    });
    
    app.listen(3000, () => {
      console.log('サーバーがポート3000で起動');
    });
    
  • connect-busboy:

    connect-busboyを使用したファイルアップロードの例

    const express = require('express');
    const connectBusboy = require('connect-busboy');
    const fs = require('fs');
    const app = express();
    
    app.use(connectBusboy());
    
    app.post('/upload', (req, res) => {
      req.busboy.on('file', (fieldname, file, filename) => {
        const writeStream = fs.createWriteStream(`./uploads/${filename}`);
        file.pipe(writeStream);
      });
      req.busboy.on('finish', () => {
        res.send('ファイルアップロード完了');
      });
    });
    
    app.listen(3000, () => {
      console.log('サーバーがポート3000で起動');
    });
    
  • connect-multiparty:

    connect-multipartyを使用したファイルアップロードの例

    const express = require('express');
    const multiparty = require('connect-multiparty');
    const fs = require('fs');
    const app = express();
    const multipartyMiddleware = multiparty();
    
    app.post('/upload', multipartyMiddleware, (req, res) => {
      const { files } = req;
      Object.keys(files).forEach(field => {
        const file = files[field];
        const writeStream = fs.createWriteStream(`./uploads/${file.originalFilename}`);
        fs.createReadStream(file.path).pipe(writeStream);
      });
      res.send('ファイルアップロード完了');
    });
    
    app.listen(3000, () => {
      console.log('サーバーがポート3000で起動');
    });
    
選び方: busboy vs formidable vs multer vs express-fileupload vs connect-busboy vs connect-multiparty
  • busboy:

    busboyは、ストリーミングAPIを提供する軽量なマルチパート解析ライブラリです。大きなファイルを効率的に処理する必要がある場合や、カスタムファイルアップロードロジックを実装したい場合に最適です。

  • formidable:

    formidableは、マルチパートフォームデータを解析し、ファイルをストリームとして処理するための強力なライブラリです。大きなファイルのアップロードやカスタム解析ロジックが必要な場合に適しています。

  • multer:

    multerは、Expressアプリケーション向けのミドルウェアで、マルチパートフォームデータを簡単に処理します。ファイルの保存先や名前をカスタマイズでき、シンプルなAPIを提供します。

  • express-fileupload:

    express-fileuploadは、Expressアプリケーション向けのシンプルで使いやすいファイルアップロードミドルウェアです。設定が簡単で、ファイルサイズ制限やアップロード進捗の追跡などの機能を提供します。

  • connect-busboy:

    connect-busboyは、busboyconnectおよびExpressミドルウェアとして統合します。既存のアプリケーションに簡単に統合でき、ストリーミング解析を利用したい場合に適しています。

  • connect-multiparty:

    connect-multipartyは、マルチパートフォームデータを解析するためのミドルウェアです。複数のファイルフィールドやテキストフィールドを同時に処理する必要がある場合に便利ですが、ストリーミング処理はサポートしていません。

busboy のREADME

Description

A node.js module for parsing incoming HTML form data.

Changes (breaking or otherwise) in v1.0.0 can be found here.

Requirements

Install

npm install busboy

Examples

  • Parsing (multipart) with default options:
const http = require('http');

const busboy = require('busboy');

http.createServer((req, res) => {
  if (req.method === 'POST') {
    console.log('POST request');
    const bb = busboy({ headers: req.headers });
    bb.on('file', (name, file, info) => {
      const { filename, encoding, mimeType } = info;
      console.log(
        `File [${name}]: filename: %j, encoding: %j, mimeType: %j`,
        filename,
        encoding,
        mimeType
      );
      file.on('data', (data) => {
        console.log(`File [${name}] got ${data.length} bytes`);
      }).on('close', () => {
        console.log(`File [${name}] done`);
      });
    });
    bb.on('field', (name, val, info) => {
      console.log(`Field [${name}]: value: %j`, val);
    });
    bb.on('close', () => {
      console.log('Done parsing form!');
      res.writeHead(303, { Connection: 'close', Location: '/' });
      res.end();
    });
    req.pipe(bb);
  } else if (req.method === 'GET') {
    res.writeHead(200, { Connection: 'close' });
    res.end(`
      <html>
        <head></head>
        <body>
          <form method="POST" enctype="multipart/form-data">
            <input type="file" name="filefield"><br />
            <input type="text" name="textfield"><br />
            <input type="submit">
          </form>
        </body>
      </html>
    `);
  }
}).listen(8000, () => {
  console.log('Listening for requests');
});

// Example output:
//
// Listening for requests
//   < ... form submitted ... >
// POST request
// File [filefield]: filename: "logo.jpg", encoding: "binary", mime: "image/jpeg"
// File [filefield] got 11912 bytes
// Field [textfield]: value: "testing! :-)"
// File [filefield] done
// Done parsing form!
  • Save all incoming files to disk:
const { randomFillSync } = require('crypto');
const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');

const busboy = require('busboy');

const random = (() => {
  const buf = Buffer.alloc(16);
  return () => randomFillSync(buf).toString('hex');
})();

http.createServer((req, res) => {
  if (req.method === 'POST') {
    const bb = busboy({ headers: req.headers });
    bb.on('file', (name, file, info) => {
      const saveTo = path.join(os.tmpdir(), `busboy-upload-${random()}`);
      file.pipe(fs.createWriteStream(saveTo));
    });
    bb.on('close', () => {
      res.writeHead(200, { 'Connection': 'close' });
      res.end(`That's all folks!`);
    });
    req.pipe(bb);
    return;
  }
  res.writeHead(404);
  res.end();
}).listen(8000, () => {
  console.log('Listening for requests');
});

API

Exports

busboy exports a single function:

( function )(< object >config) - Creates and returns a new Writable form parser stream.

  • Valid config properties:

    • headers - object - These are the HTTP headers of the incoming request, which are used by individual parsers.

    • highWaterMark - integer - highWaterMark to use for the parser stream. Default: node's stream.Writable default.

    • fileHwm - integer - highWaterMark to use for individual file streams. Default: node's stream.Readable default.

    • defCharset - string - Default character set to use when one isn't defined. Default: 'utf8'.

    • defParamCharset - string - For multipart forms, the default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). Default: 'latin1'.

    • preservePath - boolean - If paths in filenames from file parts in a 'multipart/form-data' request shall be preserved. Default: false.

    • limits - object - Various limits on incoming data. Valid properties are:

      • fieldNameSize - integer - Max field name size (in bytes). Default: 100.

      • fieldSize - integer - Max field value size (in bytes). Default: 1048576 (1MB).

      • fields - integer - Max number of non-file fields. Default: Infinity.

      • fileSize - integer - For multipart forms, the max file size (in bytes). Default: Infinity.

      • files - integer - For multipart forms, the max number of file fields. Default: Infinity.

      • parts - integer - For multipart forms, the max number of parts (fields + files). Default: Infinity.

      • headerPairs - integer - For multipart forms, the max number of header key-value pairs to parse. Default: 2000 (same as node's http module).

This function can throw exceptions if there is something wrong with the values in config. For example, if the Content-Type in headers is missing entirely, is not a supported type, or is missing the boundary for 'multipart/form-data' requests.

(Special) Parser stream events

  • file(< string >name, < Readable >stream, < object >info) - Emitted for each new file found. name contains the form field name. stream is a Readable stream containing the file's data. No transformations/conversions (e.g. base64 to raw binary) are done on the file's data. info contains the following properties:

    • filename - string - If supplied, this contains the file's filename. WARNING: You should almost never use this value as-is (especially if you are using preservePath: true in your config) as it could contain malicious input. You are better off generating your own (safe) filenames, or at the very least using a hash of the filename.

    • encoding - string - The file's 'Content-Transfer-Encoding' value.

    • mimeType - string - The file's 'Content-Type' value.

    Note: If you listen for this event, you should always consume the stream whether you care about its contents or not (you can simply do stream.resume(); if you want to discard/skip the contents), otherwise the 'finish'/'close' event will never fire on the busboy parser stream. However, if you aren't accepting files, you can either simply not listen for the 'file' event at all or set limits.files to 0, and any/all files will be automatically skipped (these skipped files will still count towards any configured limits.files and limits.parts limits though).

    Note: If a configured limits.fileSize limit was reached for a file, stream will both have a boolean property truncated set to true (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens.

  • field(< string >name, < string >value, < object >info) - Emitted for each new non-file field found. name contains the form field name. value contains the string value of the field. info contains the following properties:

    • nameTruncated - boolean - Whether name was truncated or not (due to a configured limits.fieldNameSize limit)

    • valueTruncated - boolean - Whether value was truncated or not (due to a configured limits.fieldSize limit)

    • encoding - string - The field's 'Content-Transfer-Encoding' value.

    • mimeType - string - The field's 'Content-Type' value.

  • partsLimit() - Emitted when the configured limits.parts limit has been reached. No more 'file' or 'field' events will be emitted.

  • filesLimit() - Emitted when the configured limits.files limit has been reached. No more 'file' events will be emitted.

  • fieldsLimit() - Emitted when the configured limits.fields limit has been reached. No more 'field' events will be emitted.