Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

formdata-node

Package Overview
Dependencies
Maintainers
1
Versions
76
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

formdata-node - npm Package Compare versions

Comparing version 3.7.0 to 4.0.0

@type/isFile.d.ts

1

@type/fileFromPath.d.ts
import { File, FileOptions } from "./File";
export * from "./isFile";
export declare type FileFromPathOptions = Omit<FileOptions, "lastModified">;

@@ -3,0 +4,0 @@ /**

129

@type/FormData.d.ts
/// <reference types="node" />
import { Readable } from "stream";
import { inspect } from "util";
import { File } from "./File";
export declare type FormDataFieldValue = string | File;
export declare type FormDataEntryValue = string | File;
/**
* Additional field options.
*
* @deprecated The options argument is non-standard and will be removed from this package in the next major release (4.x).
*/
export interface FormDataFieldOptions {
/**
* Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
*/
type?: string;
/**
* 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.
*/
lastModified?: number;
/**
* The name of the file.
*/
filename?: string;
}
/**
* Constructor entries for FormData

@@ -32,3 +12,2 @@ */

filename?: string;
options?: FormDataFieldOptions;
}>;

@@ -43,46 +22,15 @@ /**

#private;
/**
* Returns headers for multipart/form-data
*
* @deprecated FormData#headers property is non-standard and will be removed from this package in the next major release (4.x). Use https://npmjs.com/form-data-encoder package to serilize FormData.
*/
get headers(): {
"Content-Type": string;
"Content-Length": string;
};
/**
* Returns internal readable stream, allowing to read the FormData content
*
* @deprecated FormData#stream property is non-standard and will be removed from this package in the next major release (4.x). Use https://npmjs.com/form-data-encoder package to serilize FormData.
*/
get stream(): Readable;
/**
* @deprecated FormData#boundary property is non-standard and will be removed from this package in the next major release (4.x). Use https://npmjs.com/form-data-encoder package to serilize FormData.
*/
get boundary(): string;
constructor(entries?: FormDataConstructorEntries);
/**
* Returns computed length of the FormData content.
*
* @deprecated FormData#getComputedLength() method is non-standard and will be removed from this package in the next major release (4.x). Use https://npmjs.com/form-data-encoder package to serilize FormData.
*/
getComputedLength(): number;
/**
* Appends a new value onto an existing key inside a FormData object,
* or adds the key if it does not already exist.
*
* @param name The name of the field whose data is contained in value
* @param value The field value. You can pass any primitive type
* (including null and undefined), Buffer or Readable stream.
* Note that Arrays and Object will be converted to string
* by using String function.
* @param filename A filename of given field.
* @param options Additional field options.
* The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param filename The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*/
append(name: string, value: unknown): void;
append(name: string, value: unknown, filename?: string): void;
append(name: string, value: unknown, options?: FormDataFieldOptions & {
filename?: string;
}): void;
append(name: string, value: unknown, filename?: string, options?: FormDataFieldOptions): void;
/**

@@ -92,41 +40,36 @@ * Set a new value for an existing key inside FormData,

*
* @param name The name of the field whose data is contained in value
* @param value The field value. You can pass any primitive type
* (including null and undefined), Buffer or Readable stream.
* Note that Arrays and Object will be converted to string
* by using String function.
* @param filename A filename of given field.
* @param options Additional field options.
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param filename The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*
*/
set(name: string, value: unknown): void;
set(name: string, value: unknown, filename?: string): void;
set(name: string, value: unknown, options?: FormDataFieldOptions & {
filename?: string;
}): void;
set(name: string, value: unknown, filename?: string, options?: FormDataFieldOptions): void;
/**
* Returns the first value associated with the given name.
* Buffer and Readable values will be returned as-is.
* Returns the first value associated with a given key from within a `FormData` object.
* If you expect multiple values and want all of them, use the `getAll()` method instead.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
*/
get(name: string): FormDataFieldValue | null;
get(name: string): FormDataEntryValue | null;
/**
* Returns all the values associated with
* a given key from within a FormData object.
* Returns all the values associated with a given key from within a `FormData` object.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
*/
getAll(name: string): FormDataFieldValue[];
getAll(name: string): FormDataEntryValue[];
/**
* Check if a field with the given name exists inside FormData.
* Returns a boolean stating whether a `FormData` object contains a certain key.
*
* @param name A name of the field you want to test for.
* @param name A string representing the name of the key you want to test for.
*
* @return
* @return A boolean value.
*/
has(name: string): boolean;
/**
* Deletes a key and its value(s) from a FormData object.
* Deletes a key and its value(s) from a `FormData` object.
*

@@ -137,30 +80,26 @@ * @param name The name of the key you want to delete.

/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the **FormData** keys
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
* Each key is a `string`.
*/
keys(): Generator<string>;
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the **FormData** key/value pairs
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
* The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
entries(): Generator<[string, FormDataFieldValue]>;
entries(): Generator<[string, FormDataEntryValue]>;
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the **FormData** values
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
* Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
values(): Generator<FormDataFieldValue>;
values(): Generator<FormDataEntryValue>;
/**
* An alias for FormData#entries()
*/
[Symbol.iterator](): Generator<[string, FormDataFieldValue], any, unknown>;
[Symbol.iterator](): Generator<[string, FormDataEntryValue], any, unknown>;
/**
* Executes given callback function for each field of the FormData instance
*/
forEach(fn: (value: FormDataFieldValue, key: string, fd: FormData) => void, ctx?: unknown): void;
forEach(fn: (value: FormDataEntryValue, key: string, fd: FormData) => void, ctx?: unknown): void;
get [Symbol.toStringTag](): string;
[inspect.custom](): string;
/**
* Returns an async iterator allowing to read form-data body using **for-await-of** syntax.
* Read the [`async iteration proposal`](https://github.com/tc39/proposal-async-iteration) to get more info about async iterators.
*
* @deprecated FormData#[Symbol.asyncIterator]() method is non-standard and will be removed from this package in the next major release (4.x). Use https://npmjs.com/form-data-encoder package to serilize FormData.
*/
[Symbol.asyncIterator](): AsyncGenerator<Uint8Array, void, undefined>;
}

@@ -1,4 +0,2 @@

export { default as isFileLike } from "./util/isFile";
export * from "./FormData";
export * from "./File";
export * from "./fileFromPath";
export * from "./FormData";
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {

@@ -23,3 +33,4 @@ if (kind === "m") throw new TypeError("Private method is not writable");

const File_1 = require("./File");
const isPlainObject_1 = __importDefault(require("./util/isPlainObject"));
const isPlainObject_1 = __importDefault(require("./isPlainObject"));
__exportStar(require("./isFile"), exports);
const MESSAGE = "The requested file could not be read, "

@@ -26,0 +37,0 @@ + "typically due to permission problems that have occurred after a reference "

"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {

@@ -13,56 +7,21 @@ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _FormData_instances, _FormData_stream, _FormData_encoder, _FormData_content, _FormData_setField;
var _FormData_instances, _FormData_entries, _FormData_setEntry;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FormData = void 0;
const stream_1 = require("stream");
const path_1 = require("path");
const util_1 = require("util");
const form_data_encoder_1 = require("form-data-encoder");
const File_1 = require("./File");
const fileFromPath_1 = require("./fileFromPath");
const deprecations_1 = require("./util/deprecations");
const isFile_1 = __importDefault(require("./util/isFile"));
const isPlainObject_1 = __importDefault(require("./util/isPlainObject"));
const isReadStream_1 = __importDefault(require("./util/isReadStream"));
const getFilename_1 = __importDefault(require("./util/getFilename"));
const { isBuffer } = Buffer;
const isFile_1 = require("./isFile");
class FormData {
constructor(entries) {
_FormData_instances.add(this);
_FormData_stream.set(this, void 0);
_FormData_encoder.set(this, void 0);
_FormData_content.set(this, new Map());
__classPrivateFieldSet(this, _FormData_encoder, new form_data_encoder_1.FormDataEncoder(this), "f");
_FormData_entries.set(this, new Map());
if (entries) {
entries.forEach(({ name, value, filename, options }) => this.append(name, value, filename, options));
entries.forEach(({ name, value, filename }) => this.append(name, value, filename));
}
}
get headers() {
deprecations_1.deprecateHeaders();
return __classPrivateFieldGet(this, _FormData_encoder, "f").headers;
}
get stream() {
deprecations_1.deprecateStream();
if (!__classPrivateFieldGet(this, _FormData_stream, "f")) {
__classPrivateFieldSet(this, _FormData_stream, stream_1.Readable.from(this), "f");
}
return __classPrivateFieldGet(this, _FormData_stream, "f");
}
get boundary() {
deprecations_1.deprecateBoundary();
return __classPrivateFieldGet(this, _FormData_encoder, "f").boundary;
}
getComputedLength() {
deprecations_1.deprecateGetComputedLength();
return __classPrivateFieldGet(this, _FormData_encoder, "f").getContentLength();
}
append(name, value, filenameOrOptions, options) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setField).call(this, {
append(name, value, filename) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
value,
filenameOrOptions,
options,
filename,
append: true,

@@ -72,8 +31,7 @@ argsLength: arguments.length

}
set(name, value, filenameOrOptions, options) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setField).call(this, {
set(name, value, filename) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
value,
filenameOrOptions,
options,
filename,
append: false,

@@ -84,3 +42,3 @@ argsLength: arguments.length

get(name) {
const field = __classPrivateFieldGet(this, _FormData_content, "f").get(String(name));
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {

@@ -92,16 +50,16 @@ return null;

getAll(name) {
const field = __classPrivateFieldGet(this, _FormData_content, "f").get(String(name));
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return [];
}
return [...field];
return field.slice();
}
has(name) {
return __classPrivateFieldGet(this, _FormData_content, "f").has(String(name));
return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name));
}
delete(name) {
return void __classPrivateFieldGet(this, _FormData_content, "f").delete(String(name));
return void __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name));
}
*keys() {
for (const key of __classPrivateFieldGet(this, _FormData_content, "f").keys()) {
for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) {
yield key;

@@ -123,21 +81,5 @@ }

}
[(_FormData_stream = new WeakMap(), _FormData_encoder = new WeakMap(), _FormData_content = new WeakMap(), _FormData_instances = new WeakSet(), _FormData_setField = function _FormData_setField({ name, value, append, filenameOrOptions, options, argsLength }) {
[(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), _FormData_setEntry = function _FormData_setEntry({ name, value, append, filename, argsLength }) {
const methodName = append ? "append" : "set";
name = String(name);
if (Buffer.isBuffer(value)) {
deprecations_1.deprecateBuffer();
}
if (isReadStream_1.default(value)) {
deprecations_1.deprecateReadStream();
}
let filename;
if (isPlainObject_1.default(filenameOrOptions)) {
[options, filename] = [filenameOrOptions, undefined];
}
else {
filename = filenameOrOptions;
}
if (isPlainObject_1.default(options)) {
deprecations_1.deprecateOptions();
}
if (argsLength < 2) {

@@ -147,33 +89,21 @@ throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `

}
filename || (filename = options === null || options === void 0 ? void 0 : options.filename);
if (isFile_1.default(value) || isReadStream_1.default(value) || isBuffer(value)) {
filename = path_1.basename(filename || getFilename_1.default(value));
if (isFile_1.isFile(value)) {
value = new File_1.File([value], filename || value.name || "blob", {
type: value.type,
lastModified: value.lastModified
});
}
else if (filename) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ "parameter 2 is not one of the following types: "
+ "ReadStream | Buffer | File | Blob");
+ "parameter 2 is not of type 'Blob'.");
}
if (isReadStream_1.default(value)) {
value = fileFromPath_1.fileFromPathSync(String(value.path), filename, options);
}
else if (isBuffer(value)) {
value = new File_1.File([value], filename, options);
}
else if (isFile_1.default(value)) {
value = new File_1.File([value], filename, {
...options,
type: (options === null || options === void 0 ? void 0 : options.type) || value.type,
lastModified: (options === null || options === void 0 ? void 0 : options.lastModified) || value.lastModified
});
}
else {
value = String(value);
}
const values = __classPrivateFieldGet(this, _FormData_content, "f").get(name);
const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name);
if (!values) {
return void __classPrivateFieldGet(this, _FormData_content, "f").set(name, [value]);
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}
if (!append) {
return void __classPrivateFieldGet(this, _FormData_content, "f").set(name, [value]);
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}

@@ -195,7 +125,3 @@ values.push(value);

}
async *[Symbol.asyncIterator]() {
deprecations_1.deprecateSymbolAsyncIterator();
yield* __classPrivateFieldGet(this, _FormData_encoder, "f").encode();
}
}
exports.FormData = FormData;

@@ -12,11 +12,4 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFileLike = void 0;
var isFile_1 = require("./util/isFile");
Object.defineProperty(exports, "isFileLike", { enumerable: true, get: function () { return __importDefault(isFile_1).default; } });
__exportStar(require("./FormData"), exports);
__exportStar(require("./File"), exports);
__exportStar(require("./fileFromPath"), exports);
__exportStar(require("./FormData"), exports);

@@ -17,3 +17,4 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {

import { File } from "./File.js";
import isPlainObject from "./util/isPlainObject.js";
import isPlainObject from "./isPlainObject.js";
export * from "./isFile.js";
const MESSAGE = "The requested file could not be read, "

@@ -20,0 +21,0 @@ + "typically due to permission problems that have occurred after a reference "

@@ -1,7 +0,1 @@

var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {

@@ -12,51 +6,19 @@ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");

};
var _FormData_instances, _FormData_stream, _FormData_encoder, _FormData_content, _FormData_setField;
import { Readable } from "stream";
import { basename } from "path";
var _FormData_instances, _FormData_entries, _FormData_setEntry;
import { inspect } from "util";
import { FormDataEncoder } from "form-data-encoder";
import { File } from "./File.js";
import { fileFromPathSync } from "./fileFromPath.js";
import { deprecateBoundary, deprecateHeaders, deprecateStream, deprecateBuffer, deprecateReadStream, deprecateOptions, deprecateGetComputedLength, deprecateSymbolAsyncIterator } from "./util/deprecations.js";
import isFile from "./util/isFile.js";
import isPlainObject from "./util/isPlainObject.js";
import isReadStream from "./util/isReadStream.js";
import getFilename from "./util/getFilename.js";
const { isBuffer } = Buffer;
import { isFile } from "./isFile.js";
export class FormData {
constructor(entries) {
_FormData_instances.add(this);
_FormData_stream.set(this, void 0);
_FormData_encoder.set(this, void 0);
_FormData_content.set(this, new Map());
__classPrivateFieldSet(this, _FormData_encoder, new FormDataEncoder(this), "f");
_FormData_entries.set(this, new Map());
if (entries) {
entries.forEach(({ name, value, filename, options }) => this.append(name, value, filename, options));
entries.forEach(({ name, value, filename }) => this.append(name, value, filename));
}
}
get headers() {
deprecateHeaders();
return __classPrivateFieldGet(this, _FormData_encoder, "f").headers;
}
get stream() {
deprecateStream();
if (!__classPrivateFieldGet(this, _FormData_stream, "f")) {
__classPrivateFieldSet(this, _FormData_stream, Readable.from(this), "f");
}
return __classPrivateFieldGet(this, _FormData_stream, "f");
}
get boundary() {
deprecateBoundary();
return __classPrivateFieldGet(this, _FormData_encoder, "f").boundary;
}
getComputedLength() {
deprecateGetComputedLength();
return __classPrivateFieldGet(this, _FormData_encoder, "f").getContentLength();
}
append(name, value, filenameOrOptions, options) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setField).call(this, {
append(name, value, filename) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
value,
filenameOrOptions,
options,
filename,
append: true,

@@ -66,8 +28,7 @@ argsLength: arguments.length

}
set(name, value, filenameOrOptions, options) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setField).call(this, {
set(name, value, filename) {
return __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
value,
filenameOrOptions,
options,
filename,
append: false,

@@ -78,3 +39,3 @@ argsLength: arguments.length

get(name) {
const field = __classPrivateFieldGet(this, _FormData_content, "f").get(String(name));
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {

@@ -86,16 +47,16 @@ return null;

getAll(name) {
const field = __classPrivateFieldGet(this, _FormData_content, "f").get(String(name));
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return [];
}
return [...field];
return field.slice();
}
has(name) {
return __classPrivateFieldGet(this, _FormData_content, "f").has(String(name));
return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name));
}
delete(name) {
return void __classPrivateFieldGet(this, _FormData_content, "f").delete(String(name));
return void __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name));
}
*keys() {
for (const key of __classPrivateFieldGet(this, _FormData_content, "f").keys()) {
for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) {
yield key;

@@ -117,21 +78,5 @@ }

}
[(_FormData_stream = new WeakMap(), _FormData_encoder = new WeakMap(), _FormData_content = new WeakMap(), _FormData_instances = new WeakSet(), _FormData_setField = function _FormData_setField({ name, value, append, filenameOrOptions, options, argsLength }) {
[(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), _FormData_setEntry = function _FormData_setEntry({ name, value, append, filename, argsLength }) {
const methodName = append ? "append" : "set";
name = String(name);
if (Buffer.isBuffer(value)) {
deprecateBuffer();
}
if (isReadStream(value)) {
deprecateReadStream();
}
let filename;
if (isPlainObject(filenameOrOptions)) {
[options, filename] = [filenameOrOptions, undefined];
}
else {
filename = filenameOrOptions;
}
if (isPlainObject(options)) {
deprecateOptions();
}
if (argsLength < 2) {

@@ -141,33 +86,21 @@ throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `

}
filename || (filename = options === null || options === void 0 ? void 0 : options.filename);
if (isFile(value) || isReadStream(value) || isBuffer(value)) {
filename = basename(filename || getFilename(value));
if (isFile(value)) {
value = new File([value], filename || value.name || "blob", {
type: value.type,
lastModified: value.lastModified
});
}
else if (filename) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ "parameter 2 is not one of the following types: "
+ "ReadStream | Buffer | File | Blob");
+ "parameter 2 is not of type 'Blob'.");
}
if (isReadStream(value)) {
value = fileFromPathSync(String(value.path), filename, options);
}
else if (isBuffer(value)) {
value = new File([value], filename, options);
}
else if (isFile(value)) {
value = new File([value], filename, {
...options,
type: (options === null || options === void 0 ? void 0 : options.type) || value.type,
lastModified: (options === null || options === void 0 ? void 0 : options.lastModified) || value.lastModified
});
}
else {
value = String(value);
}
const values = __classPrivateFieldGet(this, _FormData_content, "f").get(name);
const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name);
if (!values) {
return void __classPrivateFieldGet(this, _FormData_content, "f").set(name, [value]);
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}
if (!append) {
return void __classPrivateFieldGet(this, _FormData_content, "f").set(name, [value]);
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}

@@ -189,6 +122,2 @@ values.push(value);

}
async *[Symbol.asyncIterator]() {
deprecateSymbolAsyncIterator();
yield* __classPrivateFieldGet(this, _FormData_encoder, "f").encode();
}
}

@@ -1,4 +0,2 @@

export { default as isFileLike } from "./util/isFile.js";
export * from "./FormData.js";
export * from "./File.js";
export * from "./fileFromPath.js";
export * from "./FormData.js";
{
"name": "formdata-node",
"version": "3.7.0",
"description": "FormData implementation for Node.js",
"version": "4.0.0",
"description": "Spec-compliant FormData implementation for Node.js",
"repository": "octet-stream/form-data",

@@ -21,15 +21,28 @@ "keywords": [

"types": "./@type/index.d.ts",
"typesVersions": {
"*": {
"file-from-path": [
"@type/fileFromPath.d.ts"
]
}
},
"exports": {
"node": {
"import": "./lib/esm/index.js",
"require": "./lib/cjs/index.js"
".": {
"node": {
"import": "./lib/esm/index.js",
"require": "./lib/cjs/index.js"
},
"browser": {
"import": "./lib/esm/browser.js",
"require": "./lib/cjs/browser.js"
},
"default": "./lib/esm/index.js"
},
"browser": {
"import": "./lib/esm/browser.js",
"require": "./lib/cjs/browser.js"
},
"default": "./lib/esm/index.js"
"./file-from-path": {
"import": "./lib/esm/fileFromPath.js",
"require": "./lib/cjs/fileFromPath.js"
}
},
"engines": {
"node": ">= 12.4"
"node": ">= 12.20"
},

@@ -79,5 +92,4 @@ "scripts": {

"fetch-blob": "2.1.2",
"form-data-encoder": "1.4.3",
"node-domexception": "1.0.0"
}
}
# FormData
FormData implementation for Node.js
Spec-compliant [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) implementation for Node.js

@@ -31,4 +31,2 @@ [![Code Coverage](https://codecov.io/github/octet-stream/form-data/coverage.svg?branch=master)](https://codecov.io/github/octet-stream/form-data?branch=master)

This package has its own encoder that allows to read the content from the `FormData` instances into the `multipart/form-data` format. Just use `Symbol.asyncIterator` method to get async iterator or just access `FormData#stream` property to get `Readable` stream. Note that in the next major release both of this methods will be removed in favour of [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder), which is basically the reimplementation of builtin `formdata-node` encoder that was separated from this package to allow to re-use it in different HTTP clients or use it to add some additional logic into the encoding process. See `form-data-encoder` documentation to get more information.
1. Let's take a look at minimal example with [got](https://github.com/sindresorhus/got):

@@ -39,14 +37,10 @@

// I assume Got >= 12.x is used for this example
import got from "got"
const fd = new FormData()
const form = new FormData()
fd.set("greeting", "Hello, World!")
form.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("https://httpbin.org/post", options)
got.post("https://httpbin.org/post", {body: form})
.then(res => console.log("Res: ", res.body))

@@ -56,3 +50,3 @@ .catch(err => console.error("Error: ", err))

2. Because every FormData instance (in this package) has Symbol.asyncIterator method, you can create a stream from it using `Readable.from()`:
2. If your HTTP client does not support spec-compliant FomrData, you can use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode entries:

@@ -62,35 +56,14 @@ ```js

import {FormDataEncoder} from "form-data-encoder"
import {FormData} from "formdata-node"
// Note that `node-fetch` >= 3.x have builtin support for spec-compliant FormData, sou you'll only need the `form-data-encoder` if you use `node-fetch` <= 2.x.
import fetch from "node-fetch"
const fd = new FormData()
const form = new FormData()
fd.set("field", "Some value")
form.set("field", "Some value")
const options = {
method: "post",
headers: fd.headers,
body: Readable.from(fd)
}
const encoder = new FormDataEncoder(form)
await fetch("https://httpbin.org/post", options)
```
4. Encode entries using form-data-encoder (in cases when HTTP client does not support spec-compatible FormData):
```js
import {Readable} from "stream"
import {Encoder} from "form-data-encoder"
import {FormData} from "formdata-node"
import fetch from "node-fetch"
const fd = new FormData()
fd.set("field", "Some value")
const encoder = new Encoder(fd)
const options = {

@@ -105,79 +78,57 @@ method: "post",

4. Sending files over form-data:
3. Sending files over form-data:
```js
import {createReadStream} from "fs"
import {FormData, File} from "formdata-node" // You can use `File` from fetch-blob >= 3.x
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()
const form = new FormData()
const file = new File(["My hovercraft is full of eels"], "file.txt")
fd.set("file", createReadStream("/path/to/a/file"))
form.set("file", file)
// Just like that, you can send a file with formdata-node
await fetch("https://httpbin.org/post", {method: "post", body: fd})
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
5. You can also append files using `fileFromPath` or `fileFromPathSync` helpers. It does the same thing as [`fetch-blob/from`](https://github.com/node-fetch/fetch-blob#blob-part-backed-up-by-filesystem), but returns a `File` instead of `Blob`:
4. Blobs as field's values allowed too:
```js
import {FormData, fileFromPath} from "formdata-node"
import {FormData, Blob} from "formdata-node" // You can use `Blob` from fetch-blob
import fetch from "node-fetch"
const form = new FormData()
const blob = new Blob(["Some content"], {type: "text/plain"})
const fd = new FormData()
form.set("blob", blob)
fd.set("file", await fileFromPath("/path/to/a/file"))
// Will always be returned as `File`
let file = form.get("blob")
await fetch("https://httpbin.org/post", {method: "post", body: fd})
```
// The created file has "blob" as the name by default
console.log(file.name) // -> blob
**Note that this method is preferable over the `fs.createReadStream()` and will be the only option (along with its async version) in next major release.**
// To change that, you need to set filename argument manually
form.set("file", blob, "some-file.txt")
6. And of course you can create your own File manually – formdata-node gets you covered. It has a `File` object that inherits `Blob` from [`fetch-blob`](https://github.com/node-fetch/fetch-blob) package:
file = form.get("file")
```js
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://httpbin.org/post", {method: "post", body: fd})
console.log(file.name) // -> some-file.txt
```
7. Blobs as field's values allowed too:
5. You can also append files using `fileFromPath` or `fileFromPathSync` helpers. It does the same thing as [`fetch-blob/from`](https://github.com/node-fetch/fetch-blob#blob-part-backed-up-by-filesystem), but returns a `File` instead of `Blob`:
```js
import {fileFromPath} from "formdata-node/file-from-path"
import {FormData} from "formdata-node"
import Blob from "fetch-blob"
import fetch from "node-fetch"
const fd = new FormData()
const blob = new Blob(["Some content"], {type: "text/plain"})
const form = new FormData()
fd.set("blob", blob)
form.set("file", await fileFromPath("/path/to/a/file"))
// Will always be returned as `File`
let file = fd.get("blob")
// The created file has "blob" as the name by default
console.log(file.name) // -> blob
// To change that, you need to set filename argument manually
fd.set("file", blob, "some-file.txt")
file = fd.get("file")
console.log(file.name) // -> some-file.txt
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
8. You can still use files sourced from any stream, but unlike in v2 you'll need some extra work to achieve that:
6. You can still use files sourced from any stream, but unlike in v2 you'll need some extra work to achieve that:

@@ -215,10 +166,10 @@ ```js

const fd = new FormData()
const form = new FormData()
fd.set("stream", new BlobFromStream(stream, content.length), "file.txt")
form.set("stream", new BlobFromStream(stream, content.length), "file.txt")
await fetch("https://httpbin.org/post", {method: "post", body: fd})
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
9. Note that if you don't know the length of that stream, you'll also need to handle form-data encoding manually or use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) package. This is necessary to control which headers will be sent with your HTTP request:
7. Note that if you don't know the length of that stream, you'll also need to handle form-data encoding manually or use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) package. This is necessary to control which headers will be sent with your HTTP request:

@@ -231,6 +182,6 @@ ```js

const fd = new FormData()
const form = new FormData()
// You can use file-shaped or blob-shaped objects as FormData value instead of creating separate class
fd.set("stream", {
form.set("stream", {
type: "text/plain",

@@ -244,3 +195,3 @@ name: "file.txt",

const encoder = new Encoder(fd)
const encoder = new Encoder(form)

@@ -255,3 +206,3 @@ const options = {

await fetch("https://httpbin.org/post", {method: "post", body: fd})
await fetch("https://httpbin.org/post", {method: "post", body: form})
```

@@ -272,24 +223,5 @@

#### Instance properties
##### `boundary -> {string}`
Returns a boundary string of the current `FormData` instance. Read-only property.
##### `stream -> {stream.Readable}`
**Deprecated!** This property will be removed in 4.x version. Use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode FormData into `multipart/form-data` format in case if your HTTP client does not support spec-compatible FormData implementations.
Returns an internal Readable stream. Use it to send queries, but don't push
anything into it. Read-only property.
##### `headers -> {object}`
**Deprecated!** This property will be removed in 4.x version. Use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode FormData into `multipart/form-data` format in case if your HTTP client does not support spec-compatible FormData implementations.
Returns object with `Content-Type` header. Read-only property.
#### Instance methods
##### `set(name, value[, filename, options]) -> {void}`
##### `set(name, value[, filename]) -> {void}`

@@ -299,14 +231,8 @@ Set a new value for an existing key inside **FormData**,

- **{string}** name – The name of the field whose data is contained in **value**
- **{unknown}** value – The field value. You can pass any JavaScript primitive type (including `null` and `undefined`),
[`Buffer`](https://nodejs.org/api/buffer.html#buffer_buffer), [`ReadStream`](https://nodejs.org/dist/latest/docs/api/fs.html#fs_class_fs_readstream), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
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`, `Blob` and `ReadStream`. 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`, `Blob` and `ReadStream`. 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`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
- **{string}** name – The name of the field whose data is contained in `value`.
- **{unknown}** value – The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
- **{string}** [filename = undefined] – The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
##### `append(name, value[, filename, options]) -> {void}`
##### `append(name, value[, filename]) -> {void}`

@@ -316,24 +242,19 @@ Appends a new value onto an existing key inside a FormData object,

- **{string}** name – The name of the field whose data is contained in **value**
- **{unknown}** value – The field value. You can pass any JavaScript primitive type (including `null` and `undefined`),
[`Buffer`](https://nodejs.org/api/buffer.html#buffer_buffer), [`ReadStream`](https://nodejs.org/dist/latest/docs/api/fs.html#fs_class_fs_readstream), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
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`, `Blob` and `ReadStream`. 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`, `Blob` and `ReadStream`. 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`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
##### `get(name) -> {string | File}`
- **{string}** name – The name of the field whose data is contained in `value`.
- **{unknown}** value – The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
- **{string}** [filename = undefined] – The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
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.
##### `get(name) -> {FormDataValue}`
Returns the first value associated with a given key from within a `FormData` object.
If you expect multiple values and want all of them, use the `getAll()` method instead.
- **{string}** name – A name of the value you want to retrieve.
##### `getAll(name) -> {Array<string | File>}`
##### `getAll(name) -> {Array<FormDataValue>}`
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.
Returns all the values associated with a given key from within a `FormData` object.

@@ -344,5 +265,5 @@ - **{string}** name – A name of the value you want to retrieve.

Check if a field with the given **name** exists inside **FormData**.
Returns a boolean stating whether a `FormData` object contains a certain key.
- **{string}** – A name of the field you want to test for.
- **{string}** – A string representing the name of the key you want to test for.

@@ -355,8 +276,2 @@ ##### `delete(name) -> {void}`

##### `getComputedLength() -> {number}`
**Deprecated!** This property will be removed in 4.x version. Use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode FormData into `multipart/form-data` format in case if your HTTP client does not support spec-compatible FormData implementations.
Returns computed length of the FormData content.
##### `forEach(callback[, ctx]) -> {void}`

@@ -367,3 +282,3 @@

- **{function}** callback – Function to execute for each element, taking three arguments:
+ **{string | File}** value – A value(s) of the current field.
+ **{FormDataValue}** value – A value(s) of the current field.
+ **{string}** name – Name of the current field.

@@ -375,23 +290,19 @@ + **{FormData}** fd – The FormData instance that **forEach** is being applied to

Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the **FormData** keys
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
Each key is a `string`.
##### `values() -> {Generator<string | File>}`
##### `values() -> {Generator<FormDataValue>}`
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the **FormData** values
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
##### `entries() -> {Generator<[string, string | File]>}`
##### `entries() -> {Generator<[string, FormDataValue]>}`
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the **FormData** key/value pairs
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through key/value pairs contained in this `FormData` object.
The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
##### `[Symbol.iterator]() -> {Generator<[string, string | File]>}`
##### `[Symbol.iterator]() -> {Generator<[string, FormDataValue]>}`
An alias for [`FormData#entries()`](#entries---iterator)
##### `[Symbol.asyncIterator]() -> {AsyncGenerator<Buffer>}`
**Deprecated!** This property will be removed in 4.x version. Use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode FormData into `multipart/form-data` format in case if your HTTP client does not support spec-compatible FormData implementations.
Returns an async iterator allowing to read form-data body using **for-await-of** syntax.
Read the [`async iteration proposal`](https://github.com/tc39/proposal-async-iteration) to get more info about async iterators.
### `class File extends Blob`

@@ -403,3 +314,3 @@

- **{(ArrayBufferLike | ArrayBufferView | Blob | Buffer | string)[]}** blobParts
- **{(ArrayBufferLike | ArrayBufferView | Blob | string)[]}** blobParts
- **{string}** filename – Representing the file name.

@@ -412,2 +323,4 @@ - **{object}** [options = {}] - An options object containing optional attributes for the file. Available options are as follows

Available from `formdata-node/file-from-path` subpath.
Creates a `File` referencing the one on a disk by given path.

@@ -422,2 +335,4 @@

Available from `formdata-node/file-from-path` subpath.
Creates a `File` referencing the one on a disk by given path. Synchronous version of the `fileFromPath`.

@@ -430,6 +345,8 @@

### `isFileLike(value) -> {boolean}`
### `isFile(value) -> {boolean}`
Check if given value is a File, Blob or file-look-a-like object.
Available from `formdata-node/file-from-path` subpath.
Checks if given value is a File, Blob or file-look-a-like object.
- **{unknown}** value - A value to test

@@ -442,6 +359,8 @@

- [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) documentation on MDN
- [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue) documentation on MDN.
- [`formdata-polyfill`](https://github.com/jimmywarting/FormData) HTML5 `FormData` for Browsers & NodeJS.
- [`fetch-blob`](https://github.com/bitinn/fetch-blob) a Blob implementation on node.js, originally from node-fetch.
- [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) - Encoder for multipart/form-data
- [`node-fetch`](https://github.com/node-fetch/node-fetch) a light-weight module that brings the Fetch API to Node.js
- [`fetch-blob`](https://github.com/node-fetch/fetch-blob) a Blob implementation on node.js, originally from `node-fetch`.
- [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) spec-compliant `multipart/form-data` encoder implementation.
- [`then-busboy`](https://github.com/octet-stream/then-busboy) a 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-data`](https://github.com/octet-stream/object-to-form-data) converts JavaScript object to FormData.
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc