Package Exports
- formdata-node
Readme
FormData
FormData implementation for Node.js. Built over Readable stream and async generators.
Installation
You can install this package from npm:
npm install formdata-nodeOr with yarn:
yarn add formdata-nodeUsage
Each FormData instance allows you to read its data from Readable stream,
just use FormData#stream property for that.
You can send queries via HTTP clients that supports headers setting Readable stream as body.
- Let's take a look at minimal example with got:
import {FormData} from "formdata-node"
import got from "got"
const fd = new FormData()
fd.set("greeting", "Hello, World!")
const options = {
body: fd.stream, // Set internal stream as request body
headers: fd.headers // Set headers of the current FormData instance
}
got.post("http://example.com", options)
.then(res => console.log("Res: ", res.body))
.catch(err => console.error("Error: ", err))- Sending files over form-data:
import {createReadStream} from "fs"
import {FormData} from "formdata-node"
// I assume that there's node-fetch@3 is used for this example since it has formdata-node support out of the box
// Note that they still in beta.
import fetch from "node-fetch"
const fd = new FormData()
fd.set("file", createReadStream("/path/to/a/file"))
// Just like that, you can send a file with formdata-node
await fetch("https://example.com", {method: "post", body: fd})- You can also append files using
fileFromPathSynchelper. It does the same thing asfetch-blob/from, but returns aFileinstead ofBlob
import {FormData, fileFromPathSync} from "formdata-node"
import fetch from "node-fetch"
const fd = new FormData()
fd.set("file", fileFromPathSync("/path/to/a/file"))
await fetch("https://example.com", {method: "post", body: fd})- And of course you can create your own File manually – formdata-node gets you covered. It has a
Fileobject that inheritsBlobfromfetch-blobpackage
import {FormData, File} from "formdata-node"
import fetch from "node-fetch"
const fd = new FormData()
const file = new File(["My hovercraft is full of eels"], "hovercraft.txt")
fd.set("file", file)
await fetch("https://example.com", {method: "post", body: fd})- Blobs as field's values allowed too
import {FormData} from "formdata-node"
import Blob from "fetch-blob"
const fd = new FormData()
const blob = new Blob(["Some content"], {type: "text/plain"})
fd.set("blob", blob)
fd.get("blob") // Will always be returned as `File`API
constructor FormData([entries])
Initialize new FormData instance
- {array} [entries = null] – an optional FormData initial entries. Each initial field should be passed as a collection of the objects with "name", "value" and "filename" props. See the FormData#append() for more info about the available format.
Instance properties
boundary -> {string}
Returns a boundary string of the current FormData instance. Read-only property.
stream -> {stream.Readable}
Returns an internal Readable stream. Use it to send queries, but don't push anything into it. Read-only property.
headers -> {object}
Returns object with Content-Type header. Read-only property.
Instance methods
set(name, value[, filename, options]) -> {void}
Set a new value for an existing key inside FormData, or add the new field if it does not already exist.
- {string} name – The name of the field whose data is contained in value
- {any} value – The field value. You can pass any JavaScript primitive type (including
nullandundefined),Buffer,ReadStream,BloborFile. Note that Arrays and Object will be converted to string by using String function. - {string} [filename = undefined] – A filename of given field. Can be added only for
Buffer,File,BlobandReadStream. You can set it either from and argument or options. - {object} [object = {}] - Additional field options
- {string} [object.filename = undefined] – A filename of given field. Can be added only for
Buffer,File,BlobandReadStream. You can set it either from and argument or options. - {number} [options.lastModified = Date.now()] – provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
- {string} [options.type = ""] - Returns the media type (
MIME) of the file represented by aFileobject.
append(name, value[, filename, options]) -> {void}
Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
- {string} name – The name of the field whose data is contained in value
- {any} value – The field value. You can pass any JavaScript primitive type (including
nullandundefined),Buffer,ReadStream,BloborFile. Note that Arrays and Object will be converted to string by using String function. - {string} [filename = undefined] – A filename of given field. Can be added only for
Buffer,File,BlobandReadStream. You can set it either from and argument or options. - {object} [object = {}] - Additional field options
- {string} [object.filename = undefined] – A filename of given field. Can be added only for
Buffer,File,BlobandReadStream. You can set it either from and argument or options. - {number} [options.lastModified = Date.now()] – provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
- {string} [options.type = ""] - Returns the media type (
MIME) of the file represented by aFileobject.
get(name) -> {string | File}
Returns the first value associated with the given name.
If the field has Blob, Buffer, File or ReadStream value, the File-like object will be returned.
- {string} name – A name of the value you want to retrieve.
getAll(name) -> {Array<string | File>}
Returns all the values associated with a given key from within a FormData object.
If the field has Blob, Buffer, File or ReadStream value, the File-like object will be returned.
- {string} name – A name of the value you want to retrieve.
has(name) -> {boolean}
Check if a field with the given name exists inside FormData.
- {string} – A name of the field you want to test for.
delete(name) -> {void}
Deletes a key and its value(s) from a FormData object.
- {string} name – The name of the key you want to delete.
getComputedLength() -> {Promise<number>}
Returns computed length of the FormData content.
forEach(callback[, ctx]) -> {void}
Executes a given callback for each field of the FormData instance
- {function} callback – Function to execute for each element, taking three arguments:
- {string | File} value – A value(s) of the current field.
- {string} name – Name of the current field.
- {FormData} fd – The FormData instance that forEach is being applied to
- {any} [ctx = null] – Value to use as this context when executing the given callback
keys() -> {IterableIterator<string>}
Returns an iterator allowing to go through the FormData keys
values() -> {Generator<string | File>}
Returns an iterator allowing to go through the FormData values
entries() -> {Generator<[string, string | File]>}
Returns an iterator allowing to go through the FormData key/value pairs
[Symbol.iterator]() -> {Generator<[string, string | File]>}
An alias for FormData#entries()
[Symbol.asyncIterator]() -> {AsyncGenerator<Buffer>}
Returns an async iterator allowing to read a data from internal Readable stream using for-await-of syntax.
Read the async iteration proposal to get more info about async iterators.
constructor File(blobParts, filename[, options])
The File class provides information about files. The File object inherits Blob from fetch-blob package.
- {(ArrayBufferLike | ArrayBufferView | Blob | Buffer | string)[]} blobParts
- {string} filename – Representing the file name.
- {object} [options = {}] - An options object containing optional attributes for the file. Available options are as follows
- {number} [options.lastModified = Date.now()] – provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
- {string} [options.type = ""] - Returns the media type (
MIME) of the file represented by aFileobject.
fileFromPathSync(path[, filename, options]) -> {File}
Creates a File referencing the one on a disk by given path.
- {string} path - Path to a file
- {string} [filename] - Name of the file. Will be passed as second argument in
Fileconstructor. If not presented, the file path will be used to get it. - {object} [options = {}] - File options.
- {number} [options.lastModified = Date.now()] – provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
- {string} [options.type = ""] - Returns the media type (
MIME) of the file represented by aFileobject.
Related links
FormDatainterface documentation on MDNformdata-polyfillHTML5FormDatapolyfill for Browsers.fetch-bloba Blob implementation on node.js, originally from node-fetch.then-busboya promise-based wrapper around Busboy. Process multipart/form-data content and returns it as a single object. Will be helpful to handle your data on the server-side applications.@octetstream/object-to-form-dataconverts JavaScript object to FormData.