Top Related Projects
🌐 Human-friendly and powerful HTTP request library for Node.js
Promise based HTTP client for the browser and node.js
🏊🏾 Simplified HTTP request client.
A light-weight module that brings the Fetch API to Node.js
Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
A module to create readable `"multipart/form-data"` streams. Can be used to submit forms and file uploads to other web applications.
Quick Overview
Busboy is a Node.js module for parsing incoming HTML form data, particularly file uploads and multipart/form-data content. It provides a streaming interface for efficiently handling large file uploads and form submissions without consuming excessive memory.
Pros
- Efficient streaming parser for multipart form data
- Lightweight with minimal dependencies
- Supports both files and non-file fields
- Customizable with various options for file handling and limits
Cons
- Requires manual handling of temporary files
- Documentation could be more comprehensive
- Limited built-in security features
- May require additional middleware for easier integration with web frameworks
Code Examples
Parsing a multipart form:
const http = require('http');
const Busboy = require('busboy');
http.createServer((req, res) => {
if (req.method === 'POST') {
const busboy = Busboy({ headers: req.headers });
busboy.on('file', (name, file, info) => {
const { filename, encoding, mimeType } = info;
console.log(`File [${name}]: filename: ${filename}, encoding: ${encoding}, mimeType: ${mimeType}`);
file.pipe(process.stdout);
});
busboy.on('field', (name, val, info) => {
console.log(`Field [${name}]: value: ${val}`);
});
busboy.on('close', () => {
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
req.pipe(busboy);
}
}).listen(8000);
Setting file size limits:
const busboy = Busboy({
headers: req.headers,
limits: {
fileSize: 1024 * 1024 * 5 // 5MB limit
}
});
Handling file uploads with custom naming:
const fs = require('fs');
const path = require('path');
busboy.on('file', (name, file, info) => {
const saveTo = path.join(os.tmpdir(), `busboy-upload-${Date.now()}`);
file.pipe(fs.createWriteStream(saveTo));
});
Getting Started
To use Busboy in your Node.js project:
-
Install the package:
npm install busboy
-
Import and use in your code:
const Busboy = require('busboy'); // In your request handler: const busboy = Busboy({ headers: req.headers }); busboy.on('file', (name, file, info) => { // Handle file upload }); busboy.on('field', (name, val, info) => { // Handle form fields }); req.pipe(busboy);
Remember to handle temporary files and implement necessary security measures when processing uploads.
Competitor Comparisons
🌐 Human-friendly and powerful HTTP request library for Node.js
Pros of Got
- More comprehensive HTTP client with support for various protocols and features
- Active development with frequent updates and improvements
- Extensive documentation and examples
Cons of Got
- Larger package size and potentially higher memory footprint
- May have a steeper learning curve for simple use cases
- Not specifically designed for handling multipart form data
Code Comparison
Busboy (parsing multipart form data):
const Busboy = require('busboy');
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Handle file upload
});
req.pipe(busboy);
Got (making HTTP requests):
const got = require('got');
(async () => {
const response = await got('https://api.example.com/data');
console.log(response.body);
})();
Summary
Busboy is a streaming parser for HTML form data, specifically designed for handling file uploads and multipart/form-data. Got, on the other hand, is a feature-rich HTTP client for making various types of requests. While Got offers more versatility for general HTTP operations, Busboy excels in its specific use case of parsing form data. The choice between the two depends on the project requirements and the specific functionality needed.
Promise based HTTP client for the browser and node.js
Pros of Axios
- Supports both browser and Node.js environments, offering a unified API for HTTP requests
- Provides built-in request and response interceptors for easy data manipulation
- Offers automatic request and response transformations, including JSON parsing
Cons of Axios
- Larger bundle size compared to Busboy, which may impact performance in smaller projects
- More complex setup and configuration for specific use cases like file uploads
- Lacks specialized features for handling multipart form data efficiently
Code Comparison
Axios (making a GET request):
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
Busboy (parsing multipart form data):
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
// Handle file upload
});
busboy.on('field', function(fieldname, val) {
// Handle form fields
});
While Axios is a full-featured HTTP client library, Busboy is specifically designed for parsing incoming HTML form data, including file uploads. Axios excels in making various types of HTTP requests and handling responses, whereas Busboy specializes in efficiently processing multipart form data on the server side. The choice between the two depends on the specific requirements of your project.
🏊🏾 Simplified HTTP request client.
Pros of Request
- More comprehensive HTTP client with support for various request types
- Extensive documentation and large community support
- Simpler API for making HTTP requests
Cons of Request
- Larger package size and more dependencies
- Not specialized for handling multipart form data like Busboy
- Deprecated and no longer maintained
Code Comparison
Busboy (parsing multipart form data):
const Busboy = require('busboy');
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Handle file upload
});
req.pipe(busboy);
Request (making an HTTP request):
const request = require('request');
request('http://www.example.com', (error, response, body) => {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
While both libraries deal with HTTP requests, they serve different purposes. Busboy is specialized for parsing incoming multipart form data, making it efficient for handling file uploads. Request, on the other hand, is a more general-purpose HTTP client for making outgoing requests. The choice between the two depends on the specific needs of your project.
A light-weight module that brings the Fetch API to Node.js
Pros of node-fetch
- Provides a modern, Promise-based API for making HTTP requests
- Supports both browser and Node.js environments
- Offers a simpler and more intuitive interface for handling network requests
Cons of node-fetch
- Limited to handling HTTP requests and responses
- Not designed for parsing multipart form data or file uploads
- May require additional libraries for more complex request scenarios
Code Comparison
node-fetch:
import fetch from 'node-fetch';
const response = await fetch('https://api.example.com/data');
const data = await response.json();
busboy:
const Busboy = require('busboy');
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Handle file upload
});
Summary
node-fetch is primarily focused on making HTTP requests and handling responses, while busboy specializes in parsing incoming HTML form data, particularly for file uploads. node-fetch offers a more modern and Promise-based API, making it easier to work with asynchronous operations. However, busboy excels in handling multipart form data and file uploads, which is not a primary focus of node-fetch.
Choose node-fetch for general HTTP requests and API interactions, and busboy for parsing form data and handling file uploads in server-side applications.
Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
Pros of Superagent
- More comprehensive HTTP client with support for various request types and formats
- Chainable API for easier request building and handling
- Built-in promise support for modern asynchronous programming
Cons of Superagent
- Larger package size and potentially higher overhead
- May be overkill for simple file upload scenarios
- Less specialized for handling multipart form data
Code Comparison
Busboy (file upload handling):
const Busboy = require('busboy');
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Handle file upload
});
req.pipe(busboy);
Superagent (file upload):
const superagent = require('superagent');
superagent.post('/upload')
.attach('file', '/path/to/file')
.end((err, res) => {
// Handle response
});
Busboy is specifically designed for parsing incoming HTML form data, including file uploads, making it more lightweight and focused. Superagent, on the other hand, is a full-featured HTTP client that can handle various types of requests, including file uploads, but with a more general-purpose approach. While Busboy excels in efficient multipart form parsing, Superagent offers a more versatile toolkit for HTTP interactions, making it suitable for a wider range of use cases beyond just file uploads.
A module to create readable `"multipart/form-data"` streams. Can be used to submit forms and file uploads to other web applications.
Pros of form-data
- Simpler API for creating and appending form data
- Built-in support for streams and file uploads
- Better browser compatibility for frontend use cases
Cons of form-data
- Less performant for parsing large multipart requests
- Limited options for customizing parsing behavior
- Lacks some advanced features available in Busboy
Code Comparison
form-data:
const FormData = require('form-data');
const form = new FormData();
form.append('field', 'value');
form.append('file', fs.createReadStream('/path/to/file'));
Busboy:
const Busboy = require('busboy');
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Handle file upload
});
busboy.on('field', (fieldname, val) => {
// Handle form field
});
Summary
form-data is more user-friendly and versatile, especially for creating multipart form data and handling file uploads in both browser and Node.js environments. It offers a simpler API and better cross-platform compatibility.
Busboy, on the other hand, excels in parsing multipart form data on the server-side, providing more granular control and better performance for large requests. It's more suitable for advanced use cases and high-performance server applications.
Choose form-data for ease of use and cross-platform compatibility, or Busboy for high-performance server-side parsing and advanced customization options.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Description
A node.js module for parsing incoming HTML form data.
Changes (breaking or otherwise) in v1.0.0 can be found here.
Note: If you are using node v18.0.0 or newer, please be aware of the node.js
HTTP(S) server's requestTimeout
configuration setting that is now enabled by default, which could cause upload
interruptions if the upload takes too long.
Requirements
- node.js -- v10.16.0 or newer
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 usingpreservePath: true
in yourconfig
) 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 dostream.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 setlimits.files
to0
, and any/all files will be automatically skipped (these skipped files will still count towards any configuredlimits.files
andlimits.parts
limits though).Note: If a configured
limits.fileSize
limit was reached for a file,stream
will both have a boolean propertytruncated
set totrue
(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 - Whethername
was truncated or not (due to a configuredlimits.fieldNameSize
limit) -
valueTruncated
- boolean - Whethervalue
was truncated or not (due to a configuredlimits.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.
Top Related Projects
🌐 Human-friendly and powerful HTTP request library for Node.js
Promise based HTTP client for the browser and node.js
🏊🏾 Simplified HTTP request client.
A light-weight module that brings the Fetch API to Node.js
Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
A module to create readable `"multipart/form-data"` streams. Can be used to submit forms and file uploads to other web applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot