Gathering detailed insights and metrics for form-data
Gathering detailed insights and metrics for form-data
Gathering detailed insights and metrics for form-data
Gathering detailed insights and metrics for form-data
A module to create readable `"multipart/form-data"` streams. Can be used to submit forms and file uploads to other web applications.
npm install form-data
97.7
Supply Chain
99
Quality
87.9
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,288 Stars
316 Commits
293 Forks
27 Watching
5 Branches
39 Contributors
Updated on 21 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-7.5%
15,457,321
Compared to previous day
Last week
2.5%
91,729,420
Compared to previous week
Last month
12.9%
372,593,499
Compared to previous month
Last year
11%
3,740,846,742
Compared to previous year
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.
npm install --save form-data
In this example we are constructing a form with 3 fields that contain a string, a buffer and a file stream.
1var FormData = require('form-data'); 2var fs = require('fs'); 3 4var form = new FormData(); 5form.append('my_field', 'my value'); 6form.append('my_buffer', new Buffer(10)); 7form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
Also you can use http-response stream:
1var FormData = require('form-data'); 2var http = require('http'); 3 4var form = new FormData(); 5 6http.request('http://nodejs.org/images/logo.png', function(response) { 7 form.append('my_field', 'my value'); 8 form.append('my_buffer', new Buffer(10)); 9 form.append('my_logo', response); 10});
Or @mikeal's request stream:
1var FormData = require('form-data'); 2var request = require('request'); 3 4var form = new FormData(); 5 6form.append('my_field', 'my value'); 7form.append('my_buffer', new Buffer(10)); 8form.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:
1form.submit('http://example.org/', function(err, res) { 2 // res – response object (http.IncomingMessage) // 3 res.resume(); 4}); 5
For more advanced request manipulations submit()
method returns http.ClientRequest
object, or you can choose from one of the alternative submission methods.
You can provide custom options, such as maxDataSize
:
1var FormData = require('form-data'); 2 3var form = new FormData({ maxDataSize: 20971520 }); 4form.append('my_field', 'my value'); 5form.append('my_buffer', /* something big */);
List of available options could be found in combined-stream
You can use node's http client interface:
1var http = require('http'); 2 3var request = http.request({ 4 method: 'post', 5 host: 'example.org', 6 path: '/upload', 7 headers: form.getHeaders() 8}); 9 10form.pipe(request); 11 12request.on('response', function(res) { 13 console.log(res.statusCode); 14});
Or if you would prefer the 'Content-Length'
header to be set for you:
1form.submit('example.org/upload', function(err, res) { 2 console.log(res.statusCode); 3});
To use custom headers and pre-known length in parts:
1var CRLF = '\r\n'; 2var form = new FormData(); 3 4var options = { 5 header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, 6 knownLength: 1 7}; 8 9form.append('my_buffer', buffer, options); 10 11form.submit('http://example.com/', function(err, res) { 12 if (err) throw err; 13 console.log('Done'); 14});
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:
1someModule.stream(function(err, stdout, stderr) { 2 if (err) throw err; 3 4 var form = new FormData(); 5 6 form.append('file', stdout, { 7 filename: 'unicycle.jpg', // ... or: 8 filepath: 'photos/toys/unicycle.jpg', 9 contentType: 'image/jpeg', 10 knownLength: 19806 11 }); 12 13 form.submit('http://example.com/', function(err, res) { 14 if (err) throw err; 15 console.log('Done'); 16 }); 17});
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:
1form.submit({ 2 host: 'example.com', 3 path: '/probably.php?extra=params', 4 auth: 'username:password' 5}, function(err, res) { 6 console.log(res.statusCode); 7});
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()
:
1form.submit({ 2 host: 'example.com', 3 path: '/surelynot.php', 4 headers: {'x-test-header': 'test-header-value'} 5}, function(err, res) { 6 console.log(res.statusCode); 7});
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.
1var form = new FormData(); 2form.append( 'my_string', 'my value' ); 3form.append( 'my_integer', 1 ); 4form.append( 'my_boolean', true ); 5form.append( 'my_buffer', new Buffer(10) ); 6form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )
You may provide a string for options, or an object.
1// Set filename by providing a string for options 2form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' ); 3 4// provide an object. 5form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );
This method adds the correct content-type
header to the provided array of userHeaders
.
Return the boundary of the formData. By default, the boundary consists of 26 -
followed by 24 numbers
for example:
1--------------------------515890814546601021194782
Set the boundary string, overriding the default behavior described above.
Note: The boundary must be unique and may not appear in the data.
Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.
1var form = new FormData(); 2form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) ); 3form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') ); 4 5axios.post( 'https://example.com/path/to/api', 6 form.getBuffer(), 7 form.getHeaders() 8 )
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.
Same as getLength
but synchronous.
Note: getLengthSync doesn't calculate streams length.
Returns the Content-Length
async. The callback is used to handle errors and continue once the length has been calculated
1this.getLength(function(err, length) { 2 if (err) { 3 this._error(err); 4 return; 5 } 6 7 // add content length 8 request.setHeader('Content-Length', length); 9 10 ... 11}.bind(this));
Checks if the length of added values is known.
Submit the form to a web application.
1var form = new FormData(); 2form.append( 'my_string', 'Hello World' ); 3 4form.submit( 'http://example.com/', function(err, res) { 5 // res – response object (http.IncomingMessage) // 6 res.resume(); 7} );
Returns the form data as a string. Don't use this if you are sending files or buffers, use getBuffer()
instead.
Form submission using request:
1var formData = { 2 my_field: 'my_value', 3 my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), 4}; 5 6request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { 7 if (err) { 8 return console.error('upload failed:', err); 9 } 10 console.log('Upload successful! Server responded with:', body); 11});
For more details see request readme.
You can also submit a form using node-fetch:
1var form = new FormData(); 2 3form.append('a', 1); 4 5fetch('http://example.com', { method: 'POST', body: form }) 6 .then(function(res) { 7 return res.json(); 8 }).then(function(json) { 9 console.log(json); 10 });
In Node.js you can post a file using axios:
1const form = new FormData(); 2const stream = fs.createReadStream(PATH_TO_FILE); 3 4form.append('image', stream); 5 6// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` 7const formHeaders = form.getHeaders(); 8 9axios.post('http://example.com', form, { 10 headers: { 11 ...formHeaders, 12 }, 13}) 14.then(response => response) 15.catch(error => error)
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.2.x
FormData has dropped support for node@0.10.x
.3.x
FormData has dropped support for node@4.x
.Form-Data is released under the MIT license.
No vulnerabilities found.
Reason
14 commit(s) and 7 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 7/25 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More