What is @fastify/busboy?
The @fastify/busboy package is a plugin for the Fastify web framework. It is primarily used for handling multipart/form-data, which is often used for uploading files through HTTP forms. It wraps the busboy library, providing an easy-to-use interface for parsing form submissions, especially file uploads, within Fastify applications.
What are @fastify/busboy's main functionalities?
File Upload
This feature allows for handling file uploads in a Fastify application. The code demonstrates how to register the @fastify/busboy plugin and set up a route to handle POST requests for file uploads. The multipart method is used to process the incoming file stream.
fastify.register(require('@fastify/busboy'));
fastify.post('/upload', function (req, reply) {
const mp = req.multipart(handler, function (err) {
console.log('upload completed');
reply.code(200).send();
});
function handler (field, file, filename, encoding, mimetype) {
// Perform actions with the file stream
}
});
Field Parsing
This feature is used for parsing non-file fields from a multipart/form-data request. The example shows how to collect form fields into an object and handle the form parsing completion.
fastify.register(require('@fastify/busboy'));
fastify.post('/form', function (req, reply) {
const data = {};
const mp = req.multipart(function (field, value) {
data[field] = value;
}, function (err) {
console.log('form parsing completed', data);
reply.code(200).send(data);
}, { limits: { fields: 5 } });
});
Other packages similar to @fastify/busboy
multer
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is very similar to @fastify/busboy but is designed for use with Express.js rather than Fastify. Multer provides a rich set of features for file upload handling and is widely used in the Express community.
formidable
Formidable is a Node.js module for parsing form data, especially file uploads. It can be used with any web framework, making it more flexible than @fastify/busboy in terms of compatibility. Formidable supports file uploads, including multiple files, and provides a lower-level API for handling form data.
busboy
Description
A Node.js module for parsing incoming HTML form data.
This is an officially supported fork by fastify organization of the amazing library originally created by Brian White,
aimed at addressing long-standing issues with it.
Benchmark (Mean time for 500 Kb payload, 2000 cycles, 1000 cycle warmup):
Library | Version | Mean time in nanoseconds (less is better) |
---|
busboy | 0.3.1 | 340114 |
@fastify/busboy | 1.0.0 | 270984 |
Changelog since busboy 0.31.
Requirements
Install
npm i @fastify/busboy
Examples
- Parsing (multipart) with default options:
const http = require('http');
const { inspect } = require('util');
const Busboy = require('busboy');
http.createServer((req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);
file.on('data', data => {
console.log(`File [${fieldname}] got ${data.length} bytes`);
});
file.on('end', () => {
console.log(`File [${fieldname}] Finished`);
});
});
busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
console.log(`Field [${fieldname}]: value: ${inspect(val)}`);
});
busboy.on('finish', () => {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} 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="text" name="textfield"><br>
<input type="file" name="filefield"><br>
<input type="submit">
</form>
</body></html>`);
}
}).listen(8000, () => {
console.log('Listening for requests');
});
- Save all incoming files to disk:
const http = require('http');
const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
http.createServer(function(req, res) {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var saveTo = path.join(os.tmpdir(), path.basename(fieldname));
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
return req.pipe(busboy);
}
res.writeHead(404);
res.end();
}).listen(8000, function() {
console.log('Listening for requests');
});
- Parsing (urlencoded) with default options:
const http = require('http');
const { inspect } = require('util');
const Busboy = require('busboy');
http.createServer(function(req, res) {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end('<html><head></head><body>\
<form method="POST">\
<input type="text" name="textfield"><br />\
<select name="selectfield">\
<option value="1">1</option>\
<option value="10">10</option>\
<option value="100">100</option>\
<option value="9001">9001</option>\
</select><br />\
<input type="checkbox" name="checkfield">Node.js rules!<br />\
<input type="submit">\
</form>\
</body></html>');
}
}).listen(8000, function() {
console.log('Listening for requests');
});
API
Busboy is a Writable stream
Busboy (special) events
-
file(< string >fieldname, < ReadableStream >stream, < string >filename, < string >transferEncoding, < string >mimeType) - Emitted for each new file form field found. transferEncoding
contains the 'Content-Transfer-Encoding' value for the file stream. mimeType
contains the 'Content-Type' value for the file stream.
- Note: if you listen for this event, you should always handle the
stream
no matter if you care about the file contents or not (e.g. you can simply just do stream.resume();
if you want to discard the contents), otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about any incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically and safely discarded (these discarded files do still count towards files
and parts
limits). - If a configured file size limit was reached,
stream
will both have a boolean property truncated
(best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. - The property
bytesRead
informs about the number of bytes that have been read so far.
-
field(< string >fieldname, < string >value, < boolean >fieldnameTruncated, < boolean >valueTruncated, < string >transferEncoding, < string >mimeType) - Emitted for each new non-file field found.
-
partsLimit() - Emitted when specified parts
limit has been reached. No more 'file' or 'field' events will be emitted.
-
filesLimit() - Emitted when specified files
limit has been reached. No more 'file' events will be emitted.
-
fieldsLimit() - Emitted when specified fields
limit has been reached. No more 'field' events will be emitted.
Busboy methods