multiparty
A node.js module for parsing multipart-form data requests which supports streams2
Top Related Projects
A node.js module for parsing multipart-form data requests which supports streams2
Node.js middleware for handling `multipart/form-data`.
A streaming parser for HTML form data for node.js
The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
Quick Overview
Multiparty is a Node.js module for parsing multipart/form-data
streams, commonly used for handling file uploads in web applications. It provides a robust and efficient way to process form data, including both text fields and file uploads, with support for large files and streaming.
Pros
- Efficient handling of large file uploads through streaming
- Supports both files and fields in multipart forms
- Customizable with various options for file handling and parsing
- Well-maintained and widely used in the Node.js ecosystem
Cons
- Limited to
multipart/form-data
parsing, not a general-purpose form parser - May require additional setup for more complex use cases
- Learning curve for advanced features and configurations
- Dependency on Node.js streams API, which might be challenging for beginners
Code Examples
- Basic usage for parsing a multipart form:
const multiparty = require('multiparty');
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'POST') {
const form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
if (err) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Invalid request');
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Parsed successfully');
});
}
}).listen(3000);
- Handling file uploads with custom options:
const form = new multiparty.Form({
maxFilesSize: 5 * 1024 * 1024, // 5MB limit
uploadDir: './uploads'
});
form.parse(req, (err, fields, files) => {
if (err) {
console.error('Error parsing form:', err);
return;
}
console.log('Fields:', fields);
console.log('Files:', files);
});
- Streaming file uploads:
const form = new multiparty.Form();
form.on('part', (part) => {
if (part.filename) {
// It's a file upload
part.pipe(fs.createWriteStream(`./uploads/${part.filename}`));
} else {
// It's a field
part.resume();
}
});
form.parse(req);
Getting Started
To use Multiparty in your Node.js project:
-
Install the package:
npm install multiparty
-
Import and use in your code:
const multiparty = require('multiparty'); // In your request handler const form = new multiparty.Form(); form.parse(req, (err, fields, files) => { // Handle parsed data });
Remember to handle errors and configure the form parser according to your specific requirements.
Competitor Comparisons
A node.js module for parsing multipart-form data requests which supports streams2
Pros of multiparty
- Well-established and widely used library for handling multipart/form-data
- Supports both streaming and non-streaming parsing of form data
- Provides robust error handling and security features
Cons of multiparty
- May have performance limitations for very large file uploads
- Requires more setup and configuration compared to simpler alternatives
- Limited built-in support for modern JavaScript features like Promises
Code Comparison
multiparty:
const multiparty = require('multiparty');
const form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
if (err) throw err;
console.log(fields, files);
});
Additional Notes
Since both repositories mentioned in the prompt are the same (pillarjs/multiparty), there isn't a direct comparison to be made. The information provided above focuses on the characteristics of the multiparty library itself.
multiparty is a popular choice for handling file uploads and form data parsing in Node.js applications. It offers flexibility and robustness but may require more setup compared to simpler alternatives. For projects that don't need advanced features or have simpler requirements, other libraries or built-in Node.js modules might be more suitable.
Node.js middleware for handling `multipart/form-data`.
Pros of Multer
- Seamless integration with Express.js, making it easier to use in Express-based applications
- Built-in support for handling multipart/form-data, simplifying file uploads
- More actively maintained with frequent updates and bug fixes
Cons of Multer
- Limited to handling multipart/form-data, less versatile for other types of form data
- Requires additional configuration for handling large file uploads efficiently
Code Comparison
Multiparty:
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
// Handle parsed data
});
Multer:
var upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), function(req, res) {
// Handle uploaded file
});
Key Differences
- Multiparty is a more general-purpose form parsing library, while Multer focuses specifically on file uploads
- Multer provides a more straightforward API for handling file uploads in Express applications
- Multiparty offers more granular control over the parsing process, which can be beneficial for complex form handling scenarios
Use Cases
- Choose Multer for simple file upload functionality in Express applications
- Opt for Multiparty when dealing with complex forms or requiring more control over the parsing process
A streaming parser for HTML form data for node.js
Pros of Busboy
- Faster parsing and lower memory usage
- Supports both multipart and urlencoded form data
- More flexible and customizable streaming API
Cons of Busboy
- Less mature and less widely used than Multiparty
- Requires more manual configuration and setup
- Limited built-in features compared to Multiparty
Code Comparison
Multiparty:
const multiparty = require('multiparty');
const form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
// Handle parsed data
});
Busboy:
const Busboy = require('busboy');
const busboy = new Busboy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Handle file
});
busboy.on('field', (fieldname, val) => {
// Handle field
});
req.pipe(busboy);
Both libraries are used for parsing multipart form data in Node.js applications. Multiparty offers a simpler API and more built-in features, making it easier to use for basic scenarios. Busboy, on the other hand, provides more control and flexibility, allowing developers to handle parsing events directly. Busboy's streaming approach can lead to better performance and lower memory usage, especially for large file uploads. However, it requires more manual setup and event handling. The choice between the two depends on the specific requirements of your project, such as performance needs, ease of use, and desired level of control over the parsing process.
The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
Pros of formidable
- More actively maintained with frequent updates
- Supports both multipart and JSON parsing
- Offers file upload progress tracking
Cons of formidable
- Slightly more complex API
- May have higher memory usage for large file uploads
Code Comparison
multiparty:
const multiparty = require('multiparty');
const form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
// Handle parsed data
});
formidable:
const formidable = require('formidable');
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
// Handle parsed data
});
Both libraries offer similar basic functionality for parsing multipart form data. The main differences lie in their additional features and implementation details.
formidable provides more flexibility with its options and supports various input types, while multiparty focuses specifically on multipart form parsing. formidable's progress tracking feature can be beneficial for larger file uploads, but it may come at the cost of increased memory usage.
The choice between these libraries depends on specific project requirements, such as the need for JSON parsing, progress tracking, or simpler implementation. Both are viable options for handling form data in Node.js 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 CopilotREADME
multiparty
Parse http requests with content-type multipart/form-data
, also known as file uploads.
See also busboy - a faster alternative which may be worth looking into.
Installation
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
npm install multiparty
Usage
- See examples.
Parse an incoming multipart/form-data
request.
var multiparty = require('multiparty');
var http = require('http');
var util = require('util');
http.createServer(function(req, res) {
if (req.url === '/upload' && req.method === 'POST') {
// parse a file upload
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('received upload:\n\n');
res.end(util.inspect({ fields: fields, files: files }));
});
return;
}
// show a file upload form
res.writeHead(200, { 'content-type': 'text/html' });
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
API
multiparty.Form
var form = new multiparty.Form(options)
Creates a new form. Options:
encoding
- sets encoding for the incoming form fields. Defaults toutf8
.maxFieldsSize
- Limits the amount of memory all fields (not files) can allocate in bytes. If this value is exceeded, anerror
event is emitted. The default size is 2MB.maxFields
- Limits the number of fields that will be parsed before emitting anerror
event. A file counts as a field in this case. Defaults to 1000.maxFilesSize
- Only relevant whenautoFiles
istrue
. Limits the total bytes accepted for all files combined. If this value is exceeded, anerror
event is emitted. The default isInfinity
.autoFields
- Enablesfield
events and disablespart
events for fields. This is automatically set totrue
if you add afield
listener.autoFiles
- Enablesfile
events and disablespart
events for files. This is automatically set totrue
if you add afile
listener.uploadDir
- Only relevant whenautoFiles
istrue
. The directory for placing file uploads in. You can move them later usingfs.rename()
. Defaults toos.tmpdir()
.
form.parse(request, [cb])
Parses an incoming node.js request
containing form data.This will cause
form
to emit events based off the incoming request.
var count = 0;
var form = new multiparty.Form();
// Errors may be emitted
// Note that if you are listening to 'part' events, the same error may be
// emitted from the `form` and the `part`.
form.on('error', function(err) {
console.log('Error parsing form: ' + err.stack);
});
// Parts are emitted when parsing the form
form.on('part', function(part) {
// You *must* act on the part by reading it
// NOTE: if you want to ignore it, just call "part.resume()"
if (part.filename === undefined) {
// filename is not defined when this is a field and not a file
console.log('got field named ' + part.name);
// ignore field's content
part.resume();
}
if (part.filename !== undefined) {
// filename is defined when this is a file
count++;
console.log('got file named ' + part.name);
// ignore file's content here
part.resume();
}
part.on('error', function(err) {
// decide what to do
});
});
// Close emitted after form parsed
form.on('close', function() {
console.log('Upload completed!');
res.setHeader('text/plain');
res.end('Received ' + count + ' files');
});
// Parse req
form.parse(req);
If cb
is provided, autoFields
and autoFiles
are set to true
and all
fields and files are collected and passed to the callback, removing the need to
listen to any events on form
. This is for convenience when you want to read
everything, but be sure to write cleanup code, as this will write all uploaded
files to the disk, even ones you may not be interested in.
form.parse(req, function(err, fields, files) {
Object.keys(fields).forEach(function(name) {
console.log('got field named ' + name);
});
Object.keys(files).forEach(function(name) {
console.log('got file named ' + name);
});
console.log('Upload completed!');
res.setHeader('text/plain');
res.end('Received ' + files.length + ' files');
});
fields
is an object where the property names are field names and the values
are arrays of field values.
files
is an object where the property names are field names and the values
are arrays of file objects.
form.bytesReceived
The amount of bytes received for this form so far.
form.bytesExpected
The expected number of bytes in this form.
Events
'error' (err)
Unless you supply a callback to form.parse
, you definitely want to handle
this event. Otherwise your server will crash when users submit bogus
multipart requests!
Only one 'error' event can ever be emitted, and if an 'error' event is emitted, then 'close' will not be emitted.
If the error would correspond to a certain HTTP response code, the err
object
will have a statusCode
property with the value of the suggested HTTP response
code to send back.
Note that an 'error' event will be emitted both from the form
and from the
current part
.
'part' (part)
Emitted when a part is encountered in the request. part
is a
ReadableStream
. It also has the following properties:
headers
- the headers for this part. For example, you may be interested incontent-type
.name
- the field name for this partfilename
- only if the part is an incoming filebyteOffset
- the byte offset of this part in the request bodybyteCount
- assuming that this is the last part in the request, this is the size of this part in bytes. You could use this, for example, to set theContent-Length
header if uploading to S3. If the part had aContent-Length
header then that value is used here instead.
Parts for fields are not emitted when autoFields
is on, and likewise parts
for files are not emitted when autoFiles
is on.
part
emits 'error' events! Make sure you handle them.
'aborted'
Emitted when the request is aborted. This event will be followed shortly
by an error
event. In practice you do not need to handle this event.
'progress' (bytesReceived, bytesExpected)
Emitted when a chunk of data is received for the form. The bytesReceived
argument contains the total count of bytes received for this form so far. The
bytesExpected
argument contains the total expected bytes if known, otherwise
null
.
'close'
Emitted after all parts have been parsed and emitted. Not emitted if an error
event is emitted.
If you have autoFiles
on, this is not fired until all the data has been
flushed to disk and the file handles have been closed.
This is typically when you would send your response.
'file' (name, file)
By default multiparty will not touch your hard drive. But if you add this
listener, multiparty automatically sets form.autoFiles
to true
and will
stream uploads to disk for you.
The max bytes accepted per request can be specified with maxFilesSize
.
name
- the field name for this filefile
- an object with these properties:fieldName
- same asname
- the field name for this fileoriginalFilename
- the filename that the user reports for the filepath
- the absolute path of the uploaded file on diskheaders
- the HTTP headers that were sent along with this filesize
- size of the file in bytes
'field' (name, value)
name
- field namevalue
- string field value
License
Top Related Projects
A node.js module for parsing multipart-form data requests which supports streams2
Node.js middleware for handling `multipart/form-data`.
A streaming parser for HTML form data for node.js
The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
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