From f7aaf4edc6bbb07a1315569ff2138c7cdb81d766 Mon Sep 17 00:00:00 2001 From: AkkiKrsingh2005 Date: Tue, 31 Mar 2026 01:31:22 +0530 Subject: [PATCH 1/2] docs: fix typos in documentation --- CHANGELOG.md | 2 +- docs/lib/content/configuring-npm/folders.md | 2 +- node_modules/node-gyp/gyp/docs/InputFormatReference.md | 2 +- node_modules/node-gyp/gyp/docs/LanguageSpecification.md | 2 +- node_modules/postcss-selector-parser/API.md | 2 +- node_modules/safer-buffer/Porting-Buffer.md | 6 +++--- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75666423a83a3..9970b98db27df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,7 @@ ### Bug Fixes * [`a9d242b`](https://github.com/npm/cli/commit/a9d242bc4f04440630141743949ddb0d323f90b4) [#9099](https://github.com/npm/cli/pull/9099) include all subcommands on main command help (#9099) (@wraithgar) * [`29b8407`](https://github.com/npm/cli/commit/29b8407971af1b9a2a3dcdb3849adfa04363fa7f) [#9087](https://github.com/npm/cli/pull/9087) unwrap comments and lines meant for output (#9087) (@wraithgar) -* [`b56986a`](https://github.com/npm/cli/commit/b56986acb0661fba2c80135eff3d140aa659dcf5) [#9095](https://github.com/npm/cli/pull/9095) ls: suppress false UNMET DEPENDENCYs in linked strategy (#9095) (@manzoorwanijk) +* [`b56986a`](https://github.com/npm/cli/commit/b56986acb0661fba2c80135eff3d140aa659dcf5) [#9095](https://github.com/npm/cli/pull/9095) ls: suppress false UNMET dependencies in linked strategy (#9095) (@manzoorwanijk) * [`76c76e5`](https://github.com/npm/cli/commit/76c76e5ad7cc5c7f641a92334b900c9d0c9a3fbd) [#9083](https://github.com/npm/cli/pull/9083) ci: don't error on optional deps in the lockfile (#9083) (@wraithgar) * [`a29aeee`](https://github.com/npm/cli/commit/a29aeee18f3ddc2348a8e00787d237c874642789) [#9028](https://github.com/npm/cli/pull/9028) arborist: retry bin-links on Windows EPERM (#9028) (@manzoorwanijk) * [`6565eeb`](https://github.com/npm/cli/commit/6565eeb818494e1feb4e14492804ce936b394b4a) [#9045](https://github.com/npm/cli/pull/9045) bypass packument cache to prevent ETARGET errors after publish (#9045) (@Jadu07) diff --git a/docs/lib/content/configuring-npm/folders.md b/docs/lib/content/configuring-npm/folders.md index 20458512d8b90..a057774e81ecf 100644 --- a/docs/lib/content/configuring-npm/folders.md +++ b/docs/lib/content/configuring-npm/folders.md @@ -143,7 +143,7 @@ So, that gets installed at [A]. Since the parent installation of blerg satisfies bar's dependency on `blerg@1.x`, it does not install another copy under [B]. Bar [B] also has dependencies on baz and asdf. -Because it depends on `baz@2.x`, it cannot re-use the `baz@1.2.3` installed in the parent `node_modules` folder [D], and must install its own copy [C]. +Because it depends on `baz@2.x`, it cannot reuse the `baz@1.2.3` installed in the parent `node_modules` folder [D], and must install its own copy [C]. In order to minimize duplication, npm hoists dependencies to the top level by default, so asdf is installed under [A]. Underneath bar, the `baz -> quux -> bar` dependency creates a cycle. diff --git a/node_modules/node-gyp/gyp/docs/InputFormatReference.md b/node_modules/node-gyp/gyp/docs/InputFormatReference.md index 4b114f2debca4..5899de8f78b1b 100644 --- a/node_modules/node-gyp/gyp/docs/InputFormatReference.md +++ b/node_modules/node-gyp/gyp/docs/InputFormatReference.md @@ -956,7 +956,7 @@ values, depending on the setting of `OS`: Note that when `OS` is `win`, the `include` for `_win.cc` files is processed after the `exclude` matching the same pattern, because the `sources/` list participates in [merging](#Merging) during -[conditional evaluation](#Conditonals) just like any other list +[conditional evaluation](#Conditionals) just like any other list would. This guarantees that the `_win.cc` files, previously unconditionally excluded, will be re-included when `OS` is `win`. diff --git a/node_modules/node-gyp/gyp/docs/LanguageSpecification.md b/node_modules/node-gyp/gyp/docs/LanguageSpecification.md index f8fff097ab73f..a23e7711e8948 100644 --- a/node_modules/node-gyp/gyp/docs/LanguageSpecification.md +++ b/node_modules/node-gyp/gyp/docs/LanguageSpecification.md @@ -61,7 +61,7 @@ The overall design has the following characteristics: Some up-front design principles/thoughts/TODOs: - * Re-use keywords consistently. + * Reuse keywords consistently. * Keywords that allow configuration of a platform-specific concept get prefixed appropriately: * Examples: `msvs_disabled_warnings`, `xcode_framework_dirs` diff --git a/node_modules/postcss-selector-parser/API.md b/node_modules/postcss-selector-parser/API.md index e564830b66b04..25ee1d1b85fa4 100644 --- a/node_modules/postcss-selector-parser/API.md +++ b/node_modules/postcss-selector-parser/API.md @@ -655,7 +655,7 @@ Remains `undefined` if there is no attribute value. Like `node.spaces` with the `before` and `after` values containing the spaces around the element, the parts of the attribute can also have spaces before and after them. The for each of `attribute`, `operator`, `value` and -`insensitive` there is corresponding property of the same nam in +`insensitive` there is corresponding property of the same name in `node.spaces` that has an optional `before` or `after` string containing only whitespace. diff --git a/node_modules/safer-buffer/Porting-Buffer.md b/node_modules/safer-buffer/Porting-Buffer.md index 68d86bab032fa..d94fdaf1bbf15 100644 --- a/node_modules/safer-buffer/Porting-Buffer.md +++ b/node_modules/safer-buffer/Porting-Buffer.md @@ -46,7 +46,7 @@ also find calls to deprecated `Buffer()` API. Those rules are included in some p There is a drawback, though, that it doesn't always [work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is -overriden e.g. with a polyfill, so recommended is a combination of this and some other method +overridden e.g. with a polyfill, so recommended is a combination of this and some other method described above. @@ -68,7 +68,7 @@ Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) or [node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended to avoid accidential unsafe Buffer API usage. +is recommended to avoid accidental unsafe Buffer API usage. There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. @@ -87,7 +87,7 @@ your users will not observe a runtime deprecation warning when running your code Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older Node.js versions. -You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill +You would take exactly the same steps as in [Variant 1](#variant-1), but with a polyfill `const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. Make sure that you do not use old `new Buffer` API — in any files where the line above is added, From 9ed550826652c79e6af3d627017f36cd472f9b5d Mon Sep 17 00:00:00 2001 From: ankitkumar572005 Date: Mon, 20 Apr 2026 18:12:11 +0530 Subject: [PATCH 2/2] fix: restore camelCase syntax for testing hooks --- mock-registry/lib/index.js | 2 +- .../@npmcli/run-script/lib/signal-manager.js | 2 +- node_modules/minizlib/dist/commonjs/index.js | 2 +- node_modules/minizlib/dist/esm/index.js | 2 +- .../gyp/docs/LanguageSpecification.md | 2 +- .../node-gyp/gyp/pylib/gyp/generator/msvs.py | 4 ++-- node_modules/node-gyp/gyp/pylib/gyp/input.py | 2 +- .../promise-all-reject-late/test/index.js | 2 +- workspaces/arborist/lib/arborist/reify.js | 2 +- workspaces/arborist/lib/calc-dep-flags.js | 2 +- .../test/arborist/build-ideal-tree.js | 2 +- .../content/copy-concurrently.json | 2 +- .../registry-mocks/content/coveralls.json | 2 +- .../registry-mocks/content/get-value.json | 2 +- .../registry-mocks/content/jest-worker.json | 8 ++++---- .../content/json-schema-traverse.json | 2 +- .../registry-mocks/content/node-fetch.json | 20 +++++++++---------- .../content/performance-now.json | 2 +- .../registry-mocks/content/stream-http.json | 2 +- .../registry-mocks/content/traverse.json | 2 +- .../registry-mocks/content/treport.json | 2 +- workspaces/libnpmdiff/README.md | 2 +- workspaces/libnpmexec/test/local.js | 2 +- 23 files changed, 36 insertions(+), 36 deletions(-) diff --git a/mock-registry/lib/index.js b/mock-registry/lib/index.js index b99dfe6b156aa..6710cdbb99c97 100644 --- a/mock-registry/lib/index.js +++ b/mock-registry/lib/index.js @@ -96,7 +96,7 @@ class MockRegistry { // this requires that mocks not be shared between sub tests but it helps // find mistakes quicker instead of waiting for the entire test to end t.afterEach((t) => { - t.strictSame(server.pendingMocks(), [], 'no pending mocks after each') + t.strictSame(server.pendingMocks(), [], 'no pending mocks afterEach') }) } diff --git a/node_modules/@npmcli/run-script/lib/signal-manager.js b/node_modules/@npmcli/run-script/lib/signal-manager.js index a099a4af2b9be..67e610ccc47a1 100644 --- a/node_modules/@npmcli/run-script/lib/signal-manager.js +++ b/node_modules/@npmcli/run-script/lib/signal-manager.js @@ -7,7 +7,7 @@ const forwardedSignals = [ ] // no-op, this is so receiving the signal doesn't cause us to exit immediately -// instead, we exit after all children have exited when we re-send the signal +// instead, we exit afterAll children have exited when we re-send the signal // to ourselves. see the catch handler at the bottom of run-script-pkg.js const handleSignal = signal => { for (const proc of runningProcs) { diff --git a/node_modules/minizlib/dist/commonjs/index.js b/node_modules/minizlib/dist/commonjs/index.js index 78c6536baf6be..5e658756abd4c 100644 --- a/node_modules/minizlib/dist/commonjs/index.js +++ b/node_modules/minizlib/dist/commonjs/index.js @@ -230,7 +230,7 @@ class ZlibBase extends minipass_1.Minipass { nativeHandle.close = originalNativeClose; this.#handle.close = originalClose; // `_processChunk()` adds an 'error' listener. If we don't remove it - // after each call, these handlers start piling up. + // afterEach call, these handlers start piling up. this.#handle.removeAllListeners('error'); // make sure OUR error listener is still attached tho } diff --git a/node_modules/minizlib/dist/esm/index.js b/node_modules/minizlib/dist/esm/index.js index b70ba1f2cd84f..b60cf3e3845ca 100644 --- a/node_modules/minizlib/dist/esm/index.js +++ b/node_modules/minizlib/dist/esm/index.js @@ -189,7 +189,7 @@ class ZlibBase extends Minipass { nativeHandle.close = originalNativeClose; this.#handle.close = originalClose; // `_processChunk()` adds an 'error' listener. If we don't remove it - // after each call, these handlers start piling up. + // afterEach call, these handlers start piling up. this.#handle.removeAllListeners('error'); // make sure OUR error listener is still attached tho } diff --git a/node_modules/node-gyp/gyp/docs/LanguageSpecification.md b/node_modules/node-gyp/gyp/docs/LanguageSpecification.md index a23e7711e8948..03a285d5e4911 100644 --- a/node_modules/node-gyp/gyp/docs/LanguageSpecification.md +++ b/node_modules/node-gyp/gyp/docs/LanguageSpecification.md @@ -209,7 +209,7 @@ Configuration dictionaries may also contain these elements: Conditionals may appear within any dictionary in a `.gyp` file. There are two tpes of conditionals, which differ only in the timing of their processing. `conditions` sections are processed shortly after loading -`.gyp` files, and `target_conditions` sections are processed after all +`.gyp` files, and `target_conditions` sections are processed afterAll dependencies have been computed. A conditional section is introduced with a `conditions` or diff --git a/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py b/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py index 0f14c055049ad..e4eff88b7f861 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py @@ -1077,7 +1077,7 @@ def _GenerateMSVSProject(project, options, version, generator_flags): _AddCopies(actions_to_add, spec) _WriteMSVSUserFile(project.path, version, spec) - # NOTE: this stanza must appear after all actions have been decided. + # NOTE: this stanza must appear afterAll actions have been decided. # Don't excluded sources with actions attached, or they won't run. excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add) _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded) @@ -3712,7 +3712,7 @@ def _GenerateMSBuildProject(project, options, version, generator_flags, spec): _AddActions(actions_to_add, spec, project.build_file) _AddCopies(actions_to_add, spec) - # NOTE: this stanza must appear after all actions have been decided. + # NOTE: this stanza must appear afterAll actions have been decided. # Don't excluded sources with actions attached, or they won't run. excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add) diff --git a/node_modules/node-gyp/gyp/pylib/gyp/input.py b/node_modules/node-gyp/gyp/pylib/gyp/input.py index f3a5e168f2075..0aa8c75d5fca9 100644 --- a/node_modules/node-gyp/gyp/pylib/gyp/input.py +++ b/node_modules/node-gyp/gyp/pylib/gyp/input.py @@ -1660,7 +1660,7 @@ def __repr__(self): def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will - # appear in flat_list after all of its dependencies, and before all of its + # appear in flat_list afterAll of its dependencies, and beforeAll of its # dependents. flat_list = OrderedSet() diff --git a/node_modules/promise-all-reject-late/test/index.js b/node_modules/promise-all-reject-late/test/index.js index 2d7025412cf39..dcd7cba5331be 100644 --- a/node_modules/promise-all-reject-late/test/index.js +++ b/node_modules/promise-all-reject-late/test/index.js @@ -30,7 +30,7 @@ const main = () => { const runTests = () => { const lateFail = require('../') - t.test('fail only after all promises resolve', t => { + t.test('fail only afterAll promises resolve', t => { let resolvedSlow = false const fast = () => Promise.reject('nope') const slow = () => new Promise(res => setTimeout(res, 100)) diff --git a/workspaces/arborist/lib/arborist/reify.js b/workspaces/arborist/lib/arborist/reify.js index 44ac7cd34dcbc..11d5b348f46f1 100644 --- a/workspaces/arborist/lib/arborist/reify.js +++ b/workspaces/arborist/lib/arborist/reify.js @@ -290,7 +290,7 @@ module.exports = cls => class Reifier extends cls { }) // [rollbackfn, [...actions]] - // after each step, if the process was terminated, execute the rollback + // afterEach step, if the process was terminated, execute the rollback // note that each rollback *also* calls the previous one when it's // finished, and then the first one throws the error, so we only need // a new rollback step when we have a new thing that must be done to diff --git a/workspaces/arborist/lib/calc-dep-flags.js b/workspaces/arborist/lib/calc-dep-flags.js index 5f2484858094d..79c65f37affb7 100644 --- a/workspaces/arborist/lib/calc-dep-flags.js +++ b/workspaces/arborist/lib/calc-dep-flags.js @@ -6,7 +6,7 @@ // - a non-optional node with a non-optional edge out, the edge node should not be optional // - a non-peer node with a non-peer edge out, the edge node should not be peer // If a node is changed, we add to the queue and continue until no more changes. -// Flags that remain after all this unsetting should be valid. +// Flags that remain afterAll this unsetting should be valid. // Examples: // - a node still flagged optional must only be reachable via optional edges // - a node still flagged peer must only be reachable via peer edges diff --git a/workspaces/arborist/test/arborist/build-ideal-tree.js b/workspaces/arborist/test/arborist/build-ideal-tree.js index aa632426c03e1..115525a8d29d8 100644 --- a/workspaces/arborist/test/arborist/build-ideal-tree.js +++ b/workspaces/arborist/test/arborist/build-ideal-tree.js @@ -1563,7 +1563,7 @@ t.test('more peer dep conflicts', async t => { '@isaacs/testing-peer-dep-conflict-chain-p': '1', }, }, - // XXX should this be false? it's not OUR fault, after all? + // XXX should this be false? it's not OUR fault, afterAll? // but it is a conflict in a peerSet that the root is sourcing. error: true, }, diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/copy-concurrently.json b/workspaces/arborist/test/fixtures/registry-mocks/content/copy-concurrently.json index 300f0cb581cfd..b8da4e31b305b 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/copy-concurrently.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/copy-concurrently.json @@ -429,7 +429,7 @@ } } }, - "readme": "# copy-concurrently\n\nCopy files, directories and symlinks\n\n```\nconst copy = require('copy-concurrently')\ncopy('/path/to/thing', '/new/path/thing').then(() => {\n // this is now copied\n}).catch(err => {\n // oh noooo\n})\n```\n\nCopies files, directories and symlinks. Ownership is maintained when\nrunning as root, permissions are always maintained. On Windows, if symlinks\nare unavailable then junctions will be used.\n\n## PUBLIC INTERFACE\n\n### copy(from, to, [options]) → Promise\n\nRecursively copies `from` to `to` and resolves its promise when finished. \nIf `to` already exists then the promise will be rejected with an `EEXIST`\nerror.\n\nOptions are:\n\n* maxConcurrency – (Default: `1`) The maximum number of concurrent copies to do at once.\n* recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory.\n* isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires\n an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory\n fails then we'll try making a junction instead.\n\nOptions can also include dependency injection:\n\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* writeStreamAtomic - (Default: `require('fs-write-stream-atomic')`) The\n implementation of `writeStreamAtomic` to use. Used to inject a mock.\n* getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock.\n\n## EXTENSION INTERFACE\n\nOrdinarily you'd only call `copy` above. But it's possible to use it's\ncomponent functions directly. This is useful if, say, you're writing\n[move-concurently](https://npmjs.com/package/move-concurrently).\n\n### copy.file(from, to, options) → Promise\n\nCopies an ordinary file `from` to destination `to`. Uses\n`fs-write-stream-atomic` to ensure that the file is either entirely copied\nor not at all.\n\nOptions are:\n\n* uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to\n set the user and group of `to`. If uid is present then gid must be too.\n* mode - (Optional) If set then `to` will have its perms set to `mode`.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* writeStreamAtomic - (Default `require('fs-write-stream-atomic')`) The\n implementation of `writeStreamAtomic` to use. Used to inject a mock.\n\n### copy.symlink(from, to, options) → Promise\n\nCopies a symlink `from` to destination `to`. If you're using Windows and\nsymlinking fails and what you're linking is a directory then junctions will\nbe tried instead.\n\nOptions are:\n\n* top - The top level the copy is being run from. This is used to determine\n if the symlink destination is within the set of files we're copying or\n outside it.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires\n an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory\n fails then we'll try making a junction instead.\n\n### copy.recurse(from, to, options) → Promise\n\nReads all of the files in directory `from` and adds them to the `queue`\nusing `recurseWith` (by default `copy.item`).\n\nOptions are:\n\n* queue - A [`run-queue`](https://npmjs.com/package/run-queue) object to add files found inside `from` to.\n* recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory.\n* uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to\n set the user and group of `to`. If uid is present then gid must be too.\n* mode - (Optional) If set then `to` will have its perms set to `mode`.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock.\n\n### copy.item(from, to, options) → Promise\n\nCopies some kind of `from` to destination `to`. This looks at the filetype\nand calls `copy.file`, `copy.symlink` or `copy.recurse` as appropriate.\n\nSymlink copies are queued with a priority such that they happen after all\nfile and directory copies as you can't create a junction on windows to a\nfile that doesn't exist yet.\n\nOptions are:\n\n* top - The top level the copy is being run from. This is used to determine\n if the symlink destination is within the set of files we're copying or\n outside it.\n* queue - The [`run-queue`](https://npmjs.com/package/run-queue) object to\n pass to `copy.recurse` if `from` is a directory.\n* recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory.\n* uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to\n set the user and group of `to`. If uid is present then gid must be too.\n* mode - (Optional) If set then `to` will have its perms set to `mode`.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock.\n* isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires\n an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory\n fails then we'll try making a junction instead.\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* writeStreamAtomic - (Default `require('fs-write-stream-atomic')`) The\n implementation of `writeStreamAtomic` to use. Used to inject a mock.\n", + "readme": "# copy-concurrently\n\nCopy files, directories and symlinks\n\n```\nconst copy = require('copy-concurrently')\ncopy('/path/to/thing', '/new/path/thing').then(() => {\n // this is now copied\n}).catch(err => {\n // oh noooo\n})\n```\n\nCopies files, directories and symlinks. Ownership is maintained when\nrunning as root, permissions are always maintained. On Windows, if symlinks\nare unavailable then junctions will be used.\n\n## PUBLIC INTERFACE\n\n### copy(from, to, [options]) → Promise\n\nRecursively copies `from` to `to` and resolves its promise when finished. \nIf `to` already exists then the promise will be rejected with an `EEXIST`\nerror.\n\nOptions are:\n\n* maxConcurrency – (Default: `1`) The maximum number of concurrent copies to do at once.\n* recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory.\n* isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires\n an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory\n fails then we'll try making a junction instead.\n\nOptions can also include dependency injection:\n\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* writeStreamAtomic - (Default: `require('fs-write-stream-atomic')`) The\n implementation of `writeStreamAtomic` to use. Used to inject a mock.\n* getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock.\n\n## EXTENSION INTERFACE\n\nOrdinarily you'd only call `copy` above. But it's possible to use it's\ncomponent functions directly. This is useful if, say, you're writing\n[move-concurently](https://npmjs.com/package/move-concurrently).\n\n### copy.file(from, to, options) → Promise\n\nCopies an ordinary file `from` to destination `to`. Uses\n`fs-write-stream-atomic` to ensure that the file is either entirely copied\nor not at all.\n\nOptions are:\n\n* uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to\n set the user and group of `to`. If uid is present then gid must be too.\n* mode - (Optional) If set then `to` will have its perms set to `mode`.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* writeStreamAtomic - (Default `require('fs-write-stream-atomic')`) The\n implementation of `writeStreamAtomic` to use. Used to inject a mock.\n\n### copy.symlink(from, to, options) → Promise\n\nCopies a symlink `from` to destination `to`. If you're using Windows and\nsymlinking fails and what you're linking is a directory then junctions will\nbe tried instead.\n\nOptions are:\n\n* top - The top level the copy is being run from. This is used to determine\n if the symlink destination is within the set of files we're copying or\n outside it.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires\n an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory\n fails then we'll try making a junction instead.\n\n### copy.recurse(from, to, options) → Promise\n\nReads all of the files in directory `from` and adds them to the `queue`\nusing `recurseWith` (by default `copy.item`).\n\nOptions are:\n\n* queue - A [`run-queue`](https://npmjs.com/package/run-queue) object to add files found inside `from` to.\n* recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory.\n* uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to\n set the user and group of `to`. If uid is present then gid must be too.\n* mode - (Optional) If set then `to` will have its perms set to `mode`.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock.\n\n### copy.item(from, to, options) → Promise\n\nCopies some kind of `from` to destination `to`. This looks at the filetype\nand calls `copy.file`, `copy.symlink` or `copy.recurse` as appropriate.\n\nSymlink copies are queued with a priority such that they happen afterAll\nfile and directory copies as you can't create a junction on windows to a\nfile that doesn't exist yet.\n\nOptions are:\n\n* top - The top level the copy is being run from. This is used to determine\n if the symlink destination is within the set of files we're copying or\n outside it.\n* queue - The [`run-queue`](https://npmjs.com/package/run-queue) object to\n pass to `copy.recurse` if `from` is a directory.\n* recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory.\n* uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to\n set the user and group of `to`. If uid is present then gid must be too.\n* mode - (Optional) If set then `to` will have its perms set to `mode`.\n* fs - (Default: `require('fs')`) The filesystem module to use. Can be used\n to use `graceful-fs` or to inject a mock.\n* getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock.\n* isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires\n an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory\n fails then we'll try making a junction instead.\n* Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's.\n* writeStreamAtomic - (Default `require('fs-write-stream-atomic')`) The\n implementation of `writeStreamAtomic` to use. Used to inject a mock.\n", "maintainers": [ { "email": "quitlahok@gmail.com", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/coveralls.json b/workspaces/arborist/test/fixtures/registry-mocks/content/coveralls.json index 491ff3d366e1a..da31962d811d3 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/coveralls.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/coveralls.json @@ -7018,7 +7018,7 @@ "_hasShrinkwrap": false } }, - "readme": "# node-coveralls\n\n[![Build Status][ci-image]][ci-url] [![Coverage Status][coveralls-image]][coveralls-url]\n\n[Coveralls.io](https://coveralls.io/) support for Node.js. Get the great coverage reporting of coveralls.io and add a cool coverage button (like the one above) to your README.\n\nSupported CI services: [Travis CI](https://travis-ci.org/), [CodeShip](https://codeship.com/), [CircleCI](https://circleci.com/), [Jenkins](https://jenkins.io/), [Gitlab CI](https://gitlab.com/), [AppVeyor](https://www.appveyor.com/), [Buildkite](https://buildkite.com/), [GitHub Actions CI](https://github.com/features/actions), [CodeFresh](https://codefresh.io)\n\n## Installation:\n\nAdd the latest version of `coveralls` to your package.json:\n\n```shell\nnpm install coveralls --save-dev\n```\n\nIf you're using mocha, add `mocha-lcov-reporter` to your package.json:\n\n```shell\nnpm install mocha-lcov-reporter --save-dev\n```\n\n## Usage:\n\nThis script `bin/coveralls.js` can take standard input from any tool that emits the lcov data format (including [mocha](https://mochajs.org/)'s [LCOV reporter](https://npmjs.org/package/mocha-lcov-reporter)) and send it to coveralls.io to report your code coverage there.\n\nOnce your app is instrumented for coverage, and building, you need to pipe the lcov output to `./node_modules/coveralls/bin/coveralls.js`.\n\nThis library currently supports [Travis CI](https://travis-ci.org/) with no extra effort beyond piping the lcov output to coveralls. However, if you're using a different build system, there are a few environment variables that are necessary:\n\n- `COVERALLS_SERVICE_NAME` (the name of your build system)\n- `COVERALLS_REPO_TOKEN` (the secret repo token from coveralls.io)\n- `COVERALLS_GIT_BRANCH` (the branch name)\n\nThere are optional environment variables for other build systems as well:\n\n- `COVERALLS_SERVICE_NUMBER` (an id that uniquely identifies the build)\n- `COVERALLS_SERVICE_JOB_ID` (an id that uniquely identifies the build's job)\n- `COVERALLS_RUN_AT` (a date string for the time that the job ran. RFC 3339 dates work. This defaults to your build system's date/time if you don't set it.)\n- `COVERALLS_PARALLEL` (more info here: )\n\n### GitHub Actions CI\n\nIf you are using GitHub Actions CI, you should look into [coverallsapp/github-action](https://github.com/coverallsapp/github-action).\n\nIf you prefer to use this package you can do it like this:\n\n```yml\nenv:\n COVERALLS_REPO_TOKEN: \"${{ secrets.COVERALLS_REPO_TOKEN }}\"\n COVERALLS_GIT_BRANCH: \"${{ github.ref }}\"\n```\n\n### [Jest](https://jestjs.io/)\n\n- Install [jest](https://jestjs.io/docs/en/getting-started)\n- Use the following to run tests and push files to coveralls on success:\n\n ```sh\n jest --coverage && coveralls < coverage/lcov.info\n ```\n\nCheck out an example [here](https://github.com/Ethan-Arrowood/harperdb-connect/blob/master/.travis.yml) which makes use of Travis CI build stages\n\n### [Mocha](https://mochajs.org/) + [Blanket.js](https://github.com/alex-seville/blanket)\n\n- Install [blanket.js](https://github.com/alex-seville/blanket)\n- Configure blanket according to [docs](https://github.com/alex-seville/blanket/blob/master/docs/getting_started_node.md).\n- Run your tests with a command like this:\n\n ```sh\n NODE_ENV=test YOURPACKAGE_COVERAGE=1 ./node_modules/.bin/mocha \\\n --require blanket \\\n --reporter mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\n ```\n\n### [Mocha](https://mochajs.org/) + [JSCoverage](https://github.com/fishbar/jscoverage)\n\nInstrumenting your app for coverage is probably harder than it needs to be (read [here](http://seejohncode.com/2012/03/13/setting-up-mocha-jscoverage//)), but that's also a necessary step.\n\nIn mocha, if you've got your code instrumented for coverage, the command for a Travis CI build would look something like this:\n\n```sh\nYOURPACKAGE_COVERAGE=1 ./node_modules/.bin/mocha test -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\n```\n\nCheck out an example [Makefile](https://github.com/cainus/urlgrey/blob/master/Makefile) from one of my projects for an example, especially the test-coveralls build target. Note: Travis CI runs `npm test`, so whatever target you create in your Makefile must be the target that `npm test` runs (This is set in package.json's `scripts` property).\n\n### [Istanbul](https://github.com/gotwarlost/istanbul)\n\n#### With Mocha:\n\n```sh\nistanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage\n```\n\n#### With Jasmine:\n\n```sh\nistanbul cover jasmine-node --captureExceptions spec/ && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage\n```\n\n### [Nodeunit](https://github.com/caolan/nodeunit) + [JSCoverage](https://github.com/fishbar/jscoverage)\n\nDepend on nodeunit, jscoverage and coveralls:\n\n```sh\nnpm install nodeunit jscoverage coveralls --save-dev\n```\n\nAdd a coveralls script to \"scripts\" in your `package.json`:\n\n```json\n\"scripts\": {\n \"test\": \"nodeunit test\",\n \"coveralls\": \"jscoverage lib && YOURPACKAGE_COVERAGE=1 nodeunit --reporter=lcov test | coveralls\"\n}\n```\n\nEnsure your app requires instrumented code when `process.env.YOURPACKAGE_COVERAGE` variable is defined.\n\nRun your tests with a command like this:\n\n```sh\nnpm run coveralls\n```\n\nFor detailed instructions on requiring instrumented code, running on Travis CI and submitting to coveralls [see this guide](https://github.com/alanshaw/nodeunit-lcov-coveralls-example).\n\n### [Poncho](https://github.com/deepsweet/poncho)\n\nClient-side JS code coverage using [PhantomJS](https://github.com/ariya/phantomjs), [Mocha](https://mochajs.org/) and [Blanket](https://github.com/alex-seville/blanket):\n\n- [Configure](https://mochajs.org/#running-mocha-in-the-browser) Mocha for browser\n- [Mark](https://github.com/deepsweet/poncho#usage) target script(s) with `data-cover` HTML attribute\n- Run your tests with a command like this:\n\n ```sh\n ./node_modules/.bin/poncho -R lcov test/test.html | ./node_modules/coveralls/bin/coveralls.js\n ```\n\n### [Lab](https://github.com/hapijs/lab)\n\n```sh\nlab -r lcov | ./node_modules/.bin/coveralls\n```\n\n### [nyc](https://github.com/istanbuljs/nyc)\n\nWorks with almost any testing framework. Simply execute\n`npm test` with the `nyc` bin followed by running its reporter:\n\n```shell\nnyc npm test && nyc report --reporter=text-lcov | coveralls\n```\n\n### [TAP](https://github.com/isaacs/node-tap)\n\nSimply run your tap tests with the `COVERALLS_REPO_TOKEN` environment\nvariable set and tap will automatically use `nyc` to report\ncoverage to coveralls.\n\n### Command Line Parameters\n\n```shell\nUsage: coveralls.js [-v] filepath\n```\n\n#### Optional arguments:\n\n- `-v`, `--verbose`\n- `filepath` - optionally defines the base filepath of your source files.\n\n## Running locally\n\nIf you're running locally, you must have a `.coveralls.yml` file, as documented in [their documentation](https://docs.coveralls.io/ruby-on-rails#configuration), with your `repo_token` in it; or, you must provide a `COVERALLS_REPO_TOKEN` environment variable on the command-line.\n\nIf you want to send commit data to coveralls, you can set the `COVERALLS_GIT_COMMIT` environment-variable to the commit hash you wish to reference. If you don't want to use a hash, you can set it to `HEAD` to supply coveralls with the latest commit data. This requires git to be installed and executable on the current PATH.\n\n## Contributing\n\nI generally don't accept pull requests that are untested, or break the build, because I'd like to keep the quality high (this is a coverage tool after all!).\n\nI also don't care for \"soft-versioning\" or \"optimistic versioning\" (dependencies that have ^, x, > in them, or anything other than numbers and dots). There have been too many problems with bad semantic versioning in dependencies, and I'd rather have a solid library than a bleeding edge one.\n\n\n[ci-image]: https://github.com/nickmerwin/node-coveralls/workflows/Tests/badge.svg\n[ci-url]: https://github.com/nickmerwin/node-coveralls/actions?workflow=Tests\n\n[coveralls-image]: https://coveralls.io/repos/nickmerwin/node-coveralls/badge.svg?branch=master&service=github\n[coveralls-url]: https://coveralls.io/github/nickmerwin/node-coveralls?branch=master\n", + "readme": "# node-coveralls\n\n[![Build Status][ci-image]][ci-url] [![Coverage Status][coveralls-image]][coveralls-url]\n\n[Coveralls.io](https://coveralls.io/) support for Node.js. Get the great coverage reporting of coveralls.io and add a cool coverage button (like the one above) to your README.\n\nSupported CI services: [Travis CI](https://travis-ci.org/), [CodeShip](https://codeship.com/), [CircleCI](https://circleci.com/), [Jenkins](https://jenkins.io/), [Gitlab CI](https://gitlab.com/), [AppVeyor](https://www.appveyor.com/), [Buildkite](https://buildkite.com/), [GitHub Actions CI](https://github.com/features/actions), [CodeFresh](https://codefresh.io)\n\n## Installation:\n\nAdd the latest version of `coveralls` to your package.json:\n\n```shell\nnpm install coveralls --save-dev\n```\n\nIf you're using mocha, add `mocha-lcov-reporter` to your package.json:\n\n```shell\nnpm install mocha-lcov-reporter --save-dev\n```\n\n## Usage:\n\nThis script `bin/coveralls.js` can take standard input from any tool that emits the lcov data format (including [mocha](https://mochajs.org/)'s [LCOV reporter](https://npmjs.org/package/mocha-lcov-reporter)) and send it to coveralls.io to report your code coverage there.\n\nOnce your app is instrumented for coverage, and building, you need to pipe the lcov output to `./node_modules/coveralls/bin/coveralls.js`.\n\nThis library currently supports [Travis CI](https://travis-ci.org/) with no extra effort beyond piping the lcov output to coveralls. However, if you're using a different build system, there are a few environment variables that are necessary:\n\n- `COVERALLS_SERVICE_NAME` (the name of your build system)\n- `COVERALLS_REPO_TOKEN` (the secret repo token from coveralls.io)\n- `COVERALLS_GIT_BRANCH` (the branch name)\n\nThere are optional environment variables for other build systems as well:\n\n- `COVERALLS_SERVICE_NUMBER` (an id that uniquely identifies the build)\n- `COVERALLS_SERVICE_JOB_ID` (an id that uniquely identifies the build's job)\n- `COVERALLS_RUN_AT` (a date string for the time that the job ran. RFC 3339 dates work. This defaults to your build system's date/time if you don't set it.)\n- `COVERALLS_PARALLEL` (more info here: )\n\n### GitHub Actions CI\n\nIf you are using GitHub Actions CI, you should look into [coverallsapp/github-action](https://github.com/coverallsapp/github-action).\n\nIf you prefer to use this package you can do it like this:\n\n```yml\nenv:\n COVERALLS_REPO_TOKEN: \"${{ secrets.COVERALLS_REPO_TOKEN }}\"\n COVERALLS_GIT_BRANCH: \"${{ github.ref }}\"\n```\n\n### [Jest](https://jestjs.io/)\n\n- Install [jest](https://jestjs.io/docs/en/getting-started)\n- Use the following to run tests and push files to coveralls on success:\n\n ```sh\n jest --coverage && coveralls < coverage/lcov.info\n ```\n\nCheck out an example [here](https://github.com/Ethan-Arrowood/harperdb-connect/blob/master/.travis.yml) which makes use of Travis CI build stages\n\n### [Mocha](https://mochajs.org/) + [Blanket.js](https://github.com/alex-seville/blanket)\n\n- Install [blanket.js](https://github.com/alex-seville/blanket)\n- Configure blanket according to [docs](https://github.com/alex-seville/blanket/blob/master/docs/getting_started_node.md).\n- Run your tests with a command like this:\n\n ```sh\n NODE_ENV=test YOURPACKAGE_COVERAGE=1 ./node_modules/.bin/mocha \\\n --require blanket \\\n --reporter mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\n ```\n\n### [Mocha](https://mochajs.org/) + [JSCoverage](https://github.com/fishbar/jscoverage)\n\nInstrumenting your app for coverage is probably harder than it needs to be (read [here](http://seejohncode.com/2012/03/13/setting-up-mocha-jscoverage//)), but that's also a necessary step.\n\nIn mocha, if you've got your code instrumented for coverage, the command for a Travis CI build would look something like this:\n\n```sh\nYOURPACKAGE_COVERAGE=1 ./node_modules/.bin/mocha test -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\n```\n\nCheck out an example [Makefile](https://github.com/cainus/urlgrey/blob/master/Makefile) from one of my projects for an example, especially the test-coveralls build target. Note: Travis CI runs `npm test`, so whatever target you create in your Makefile must be the target that `npm test` runs (This is set in package.json's `scripts` property).\n\n### [Istanbul](https://github.com/gotwarlost/istanbul)\n\n#### With Mocha:\n\n```sh\nistanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage\n```\n\n#### With Jasmine:\n\n```sh\nistanbul cover jasmine-node --captureExceptions spec/ && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage\n```\n\n### [Nodeunit](https://github.com/caolan/nodeunit) + [JSCoverage](https://github.com/fishbar/jscoverage)\n\nDepend on nodeunit, jscoverage and coveralls:\n\n```sh\nnpm install nodeunit jscoverage coveralls --save-dev\n```\n\nAdd a coveralls script to \"scripts\" in your `package.json`:\n\n```json\n\"scripts\": {\n \"test\": \"nodeunit test\",\n \"coveralls\": \"jscoverage lib && YOURPACKAGE_COVERAGE=1 nodeunit --reporter=lcov test | coveralls\"\n}\n```\n\nEnsure your app requires instrumented code when `process.env.YOURPACKAGE_COVERAGE` variable is defined.\n\nRun your tests with a command like this:\n\n```sh\nnpm run coveralls\n```\n\nFor detailed instructions on requiring instrumented code, running on Travis CI and submitting to coveralls [see this guide](https://github.com/alanshaw/nodeunit-lcov-coveralls-example).\n\n### [Poncho](https://github.com/deepsweet/poncho)\n\nClient-side JS code coverage using [PhantomJS](https://github.com/ariya/phantomjs), [Mocha](https://mochajs.org/) and [Blanket](https://github.com/alex-seville/blanket):\n\n- [Configure](https://mochajs.org/#running-mocha-in-the-browser) Mocha for browser\n- [Mark](https://github.com/deepsweet/poncho#usage) target script(s) with `data-cover` HTML attribute\n- Run your tests with a command like this:\n\n ```sh\n ./node_modules/.bin/poncho -R lcov test/test.html | ./node_modules/coveralls/bin/coveralls.js\n ```\n\n### [Lab](https://github.com/hapijs/lab)\n\n```sh\nlab -r lcov | ./node_modules/.bin/coveralls\n```\n\n### [nyc](https://github.com/istanbuljs/nyc)\n\nWorks with almost any testing framework. Simply execute\n`npm test` with the `nyc` bin followed by running its reporter:\n\n```shell\nnyc npm test && nyc report --reporter=text-lcov | coveralls\n```\n\n### [TAP](https://github.com/isaacs/node-tap)\n\nSimply run your tap tests with the `COVERALLS_REPO_TOKEN` environment\nvariable set and tap will automatically use `nyc` to report\ncoverage to coveralls.\n\n### Command Line Parameters\n\n```shell\nUsage: coveralls.js [-v] filepath\n```\n\n#### Optional arguments:\n\n- `-v`, `--verbose`\n- `filepath` - optionally defines the base filepath of your source files.\n\n## Running locally\n\nIf you're running locally, you must have a `.coveralls.yml` file, as documented in [their documentation](https://docs.coveralls.io/ruby-on-rails#configuration), with your `repo_token` in it; or, you must provide a `COVERALLS_REPO_TOKEN` environment variable on the command-line.\n\nIf you want to send commit data to coveralls, you can set the `COVERALLS_GIT_COMMIT` environment-variable to the commit hash you wish to reference. If you don't want to use a hash, you can set it to `HEAD` to supply coveralls with the latest commit data. This requires git to be installed and executable on the current PATH.\n\n## Contributing\n\nI generally don't accept pull requests that are untested, or break the build, because I'd like to keep the quality high (this is a coverage tool afterAll!).\n\nI also don't care for \"soft-versioning\" or \"optimistic versioning\" (dependencies that have ^, x, > in them, or anything other than numbers and dots). There have been too many problems with bad semantic versioning in dependencies, and I'd rather have a solid library than a bleeding edge one.\n\n\n[ci-image]: https://github.com/nickmerwin/node-coveralls/workflows/Tests/badge.svg\n[ci-url]: https://github.com/nickmerwin/node-coveralls/actions?workflow=Tests\n\n[coveralls-image]: https://coveralls.io/repos/nickmerwin/node-coveralls/badge.svg?branch=master&service=github\n[coveralls-url]: https://coveralls.io/github/nickmerwin/node-coveralls?branch=master\n", "maintainers": [ { "email": "gregg@caines.ca", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/get-value.json b/workspaces/arborist/test/fixtures/registry-mocks/content/get-value.json index 22d7d063fd43a..149ee8c564373 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/get-value.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/get-value.json @@ -53,7 +53,7 @@ "latest": "3.0.1" }, "description": "Use property paths like 'a.b.c' to get a nested value from an object. Even works when keys have dots in them (no other dot-prop library can do this!).", - "readme": "# get-value [![NPM version](https://img.shields.io/npm/v/get-value.svg?style=flat)](https://www.npmjs.com/package/get-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/get-value.svg?style=flat)](https://npmjs.org/package/get-value) [![NPM total downloads](https://img.shields.io/npm/dt/get-value.svg?style=flat)](https://npmjs.org/package/get-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/get-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/get-value)\n\n> Use property paths like 'a.b.c' to get a nested value from an object. Even works when keys have dots in them (no other dot-prop library can do this!).\n\nPlease consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.\n\n## Table of Contents\n\n
\nDetails\n\n- [Install](#install)\n- [Usage](#usage)\n * [Supports keys with dots](#supports-keys-with-dots)\n * [Supports arrays](#supports-arrays)\n * [Supports functions](#supports-functions)\n * [Supports passing object path as an array](#supports-passing-object-path-as-an-array)\n- [Options](#options)\n * [options.default](#optionsdefault)\n * [options.isValid](#optionsisvalid)\n * [options.split](#optionssplit)\n * [options.separator](#optionsseparator)\n * [options.join](#optionsjoin)\n * [options.joinChar](#optionsjoinchar)\n- [Benchmarks](#benchmarks)\n * [Running the benchmarks](#running-the-benchmarks)\n- [Release history](#release-history)\n * [v3.0.0](#v300)\n- [About](#about)\n\n
\n\n## Install\n\nInstall with [npm](https://www.npmjs.com/):\n\n```sh\n$ npm install --save get-value\n```\n\n## Usage\n\nSee the [unit tests](test/test.js) for many more examples.\n\n```js\nconst get = require('foo');\nconst obj = { a: { b: { c: { d: 'foo' } } } };\n\nconsole.log(get(obj)); //=> { a: { b: { c: { d: 'foo' } } } };\nconsole.log(get(obj, 'a')); //=> { b: { c: { d: 'foo' } } }\nconsole.log(get(obj, 'a.b')); //=> { c: { d: 'foo' } }\nconsole.log(get(obj, 'a.b.c')); //=> { d: 'foo' }\nconsole.log(get(obj, 'a.b.c.d')); //=> 'foo'\n```\n\n### Supports keys with dots\n\nUnlike other dot-prop libraries, get-value works when keys have dots in them:\n\n```js\nconsole.log(get({ 'a.b': { c: 'd' } }, 'a.b.c'));\n//=> 'd'\n\nconsole.log(get({ 'a.b': { c: { 'd.e': 'f' } } }, 'a.b.c.d.e'));\n//=> 'f'\n```\n\n### Supports arrays\n\n```js\nconsole.log(get({ a: { b: { c: { d: 'foo' } } }, e: [{ f: 'g' }, { f: 'h' }] }, 'e.1.f')); \n//=> 'h'\n\nconsole.log(get({ a: { b: [{ c: 'd' }] } }, 'a.b.0.c')); \n//=> 'f'\n\nconsole.log(get({ a: { b: [{ c: 'd' }, { e: 'f' }] } }, 'a.b.1.e'));\n//=> 'f'\n```\n\n### Supports functions\n\n```js\nfunction foo() {}\nfoo.bar = { baz: 'qux' };\n\nconsole.log(get(foo)); \n//=> { [Function: foo] bar: { baz: 'qux' } }\n\nconsole.log(get(foo, 'bar')); \n//=> { baz: 'qux' }\n\nconsole.log(get(foo, 'bar.baz')); \n//=> qux\n```\n\n### Supports passing object path as an array\n\nSlighly improve performance by passing an array of strings to use as object path segments (this is also useful when you need to dynamically build up the path segments):\n\n```js\nconsole.log(get({ a: { b: 'c' } }, ['a', 'b']));\n//=> 'c'\n```\n\n## Options\n\n### options.default\n\n**Type**: `any`\n\n**Default**: `undefined`\n\nThe default value to return when get-value cannot resolve a value from the given object.\n\n```js\nconst obj = { foo: { a: { b: { c: { d: 'e' } } } } };\nconsole.log(get(obj, 'foo.a.b.c.d', { default: true })); //=> 'e'\nconsole.log(get(obj, 'foo.bar.baz', { default: true })); //=> true\nconsole.log(get(obj, 'foo.bar.baz', { default: false })); //=> false\nconsole.log(get(obj, 'foo.bar.baz', { default: null })); //=> null\n\n// you can also pass the default value as the last argument\n// (this is necessary if the default value is an object)\nconsole.log(get(obj, 'foo.a.b.c.d', true)); //=> 'e'\nconsole.log(get(obj, 'foo.bar.baz', true)); //=> true\nconsole.log(get(obj, 'foo.bar.baz', false)); //=> false\nconsole.log(get(obj, 'foo.bar.baz', null)); //=> null\n```\n\n### options.isValid\n\n**Type**: `function`\n\n**Default**: `true`\n\nIf defined, this function is called on each resolved value. Useful if you want to do `.hasOwnProperty` or `Object.prototype.propertyIsEnumerable`.\n\n```js\nconst isEnumerable = Object.prototype.propertyIsEnumerable;\nconst options = {\n isValid: (key, obj) => isEnumerable.call(obj, key)\n};\n\nconst obj = {};\nObject.defineProperty(obj, 'foo', { value: 'bar', enumerable: false });\n\nconsole.log(get(obj, 'foo', options)); //=> undefined\nconsole.log(get({}, 'hasOwnProperty', options)); //=> undefined\nconsole.log(get({}, 'constructor', options)); //=> undefined\n\n// without \"isValid\" check\nconsole.log(get(obj, 'foo', options)); //=> bar\nconsole.log(get({}, 'hasOwnProperty', options)); //=> [Function: hasOwnProperty]\nconsole.log(get({}, 'constructor', options)); //=> [Function: Object]\n```\n\n### options.split\n\n**Type**: `function`\n\n**Default**: `String.split()`\n\nCustom function to use for splitting the string into object path segments.\n\n```js\nconst obj = { 'a.b': { c: { d: 'e' } } };\n\n// example of using a string to split the object path\nconst options = { split: path => path.split('/') };\nconsole.log(get(obj, 'a.b/c/d', options)); //=> 'e'\n\n// example of using a regex to split the object path\n// (removing escaped dots is unnecessary, this is just an example)\nconst options = { split: path => path.split(/\\\\?\\./) };\nconsole.log(get(obj, 'a\\\\.b.c.d', options)); //=> 'e'\n```\n\n### options.separator\n\n**Type**: `string|regex`\n\n**Default**: `.`\n\nThe separator to use for spliting the string (this is probably not needed when `options.split` is used).\n\n```js\nconst obj = { 'a.b': { c: { d: 'e' } } };\n\nconsole.log(get(obj, 'a.b/c/d', { separator: '/' })); \n//=> 'e'\n\nconsole.log(get(obj, 'a\\\\.b.c.d', { separator: /\\\\?\\./ })); \n//=> 'e'\n```\n\n### options.join\n\n**Type**: `function`\n\n**Default**: `Array.join()`\n\nCustomize how the object path is created when iterating over path segments.\n\n```js\nconst obj = { 'a/b': { c: { d: 'e' } } };\nconst options = {\n // when segs === ['a', 'b'] use a \"/\" to join, otherwise use a \".\"\n join: segs => segs.join(segs[0] === 'a' ? '/' : '.')\n};\n\nconsole.log(get(obj, 'a.b.c.d', options));\n//=> 'e'\n```\n\n### options.joinChar\n\n**Type**: `string`\n\n**Default**: `.`\n\nThe character to use when re-joining the string to check for keys with dots in them (this is probably not needed when `options.join` is used). This can be a different value than the separator, since the separator can be a string or regex.\n\n```js\nconst target = { 'a-b': { c: { d: 'e' } } };\nconst options = { joinChar: '-' };\nconsole.log(get(target, 'a.b.c.d', options)); \n//=> 'e'\n```\n\n## Benchmarks\n\n_(benchmarks were run on a MacBook Pro 2.5 GHz Intel Core i7, 16 GB 1600 MHz DDR3)_.\n\nget-value is more reliable and has more features than dot-prop, without sacrificing performance.\n\n```\n# deep (175 bytes)\n dot-prop x 883,166 ops/sec ±0.93% (86 runs sampled)\n get-value x 1,448,928 ops/sec ±1.53% (87 runs sampled)\n getobject x 213,797 ops/sec ±0.85% (90 runs sampled)\n object-path x 184,347 ops/sec ±2.48% (85 runs sampled)\n\n fastest is get-value (by 339% avg)\n\n# root (210 bytes)\n dot-prop x 3,905,828 ops/sec ±1.36% (87 runs sampled)\n get-value x 16,391,934 ops/sec ±1.43% (83 runs sampled)\n getobject x 1,200,021 ops/sec ±1.81% (88 runs sampled)\n object-path x 2,788,494 ops/sec ±1.81% (86 runs sampled)\n\n fastest is get-value (by 623% avg)\n\n# shallow (84 bytes)\n dot-prop x 2,553,558 ops/sec ±0.89% (89 runs sampled)\n get-value x 3,070,159 ops/sec ±0.88% (90 runs sampled)\n getobject x 726,670 ops/sec ±0.81% (86 runs sampled)\n object-path x 922,351 ops/sec ±2.05% (86 runs sampled)\n\n fastest is get-value (by 219% avg)\n\n```\n\n### Running the benchmarks\n\nClone this library into a local directory:\n\n```sh\n$ git clone https://github.com/jonschlinkert/get-value.git\n```\n\nThen install devDependencies and run benchmarks:\n\n```sh\n$ npm install && node benchmark\n```\n\n## Release history\n\n### v3.0.0\n\n* Improved support for escaping. It's no longer necessary to use backslashes to escape keys.\n* Adds `options.default` for defining a default value to return when no value is resolved.\n* Adds `options.isValid` to allow the user to check the object after each iteration.\n* Adds `options.separator` for customizing character to split on.\n* Adds `options.split` for customizing how the object path is split.\n* Adds `options.join` for customizing how the object path is joined when iterating over path segments.\n* Adds `options.joinChar` for customizing the join character.\n\n## About\n\n
\nContributing\n\nPull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).\n\n
\n\n
\nRunning Tests\n\nRunning and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:\n\n```sh\n$ npm install && npm test\n```\n\n
\n\n
\nBuilding docs\n\n_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_\n\nTo generate the readme, run the following command:\n\n```sh\n$ npm install -g verbose/verb#dev verb-generate-readme && verb\n```\n\n
\n\n### Related projects\n\nYou might also be interested in these projects:\n\n* [has-any-deep](https://www.npmjs.com/package/has-any-deep): Return true if `key` exists deeply on the given object. | [homepage](https://github.com/jonschlinkert/has-any-deep \"Return true if `key` exists deeply on the given object. \")\n* [has-any](https://www.npmjs.com/package/has-any): Returns true if an object has any of the specified keys. | [homepage](https://github.com/jonschlinkert/has-any \"Returns true if an object has any of the specified keys.\")\n* [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value \"Returns true if a value exists, false if empty. Works with deeply nested values using object paths.\")\n* [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value \"Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.\")\n* [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value \"Delete nested properties from an object using dot notation.\")\n\n### Contributors\n\n| **Commits** | **Contributor** | \n| --- | --- |\n| 81 | [jonschlinkert](https://github.com/jonschlinkert) |\n| 2 | [ianwalter](https://github.com/ianwalter) |\n| 1 | [doowb](https://github.com/doowb) |\n\n### Author\n\n**Jon Schlinkert**\n\n* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)\n* [GitHub Profile](https://github.com/jonschlinkert)\n* [Twitter Profile](https://twitter.com/jonschlinkert)\n\n### License\n\nCopyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).\nReleased under the [MIT License](LICENSE).\n\n***\n\n_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on March 07, 2018._", + "readme": "# get-value [![NPM version](https://img.shields.io/npm/v/get-value.svg?style=flat)](https://www.npmjs.com/package/get-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/get-value.svg?style=flat)](https://npmjs.org/package/get-value) [![NPM total downloads](https://img.shields.io/npm/dt/get-value.svg?style=flat)](https://npmjs.org/package/get-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/get-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/get-value)\n\n> Use property paths like 'a.b.c' to get a nested value from an object. Even works when keys have dots in them (no other dot-prop library can do this!).\n\nPlease consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.\n\n## Table of Contents\n\n
\nDetails\n\n- [Install](#install)\n- [Usage](#usage)\n * [Supports keys with dots](#supports-keys-with-dots)\n * [Supports arrays](#supports-arrays)\n * [Supports functions](#supports-functions)\n * [Supports passing object path as an array](#supports-passing-object-path-as-an-array)\n- [Options](#options)\n * [options.default](#optionsdefault)\n * [options.isValid](#optionsisvalid)\n * [options.split](#optionssplit)\n * [options.separator](#optionsseparator)\n * [options.join](#optionsjoin)\n * [options.joinChar](#optionsjoinchar)\n- [Benchmarks](#benchmarks)\n * [Running the benchmarks](#running-the-benchmarks)\n- [Release history](#release-history)\n * [v3.0.0](#v300)\n- [About](#about)\n\n
\n\n## Install\n\nInstall with [npm](https://www.npmjs.com/):\n\n```sh\n$ npm install --save get-value\n```\n\n## Usage\n\nSee the [unit tests](test/test.js) for many more examples.\n\n```js\nconst get = require('foo');\nconst obj = { a: { b: { c: { d: 'foo' } } } };\n\nconsole.log(get(obj)); //=> { a: { b: { c: { d: 'foo' } } } };\nconsole.log(get(obj, 'a')); //=> { b: { c: { d: 'foo' } } }\nconsole.log(get(obj, 'a.b')); //=> { c: { d: 'foo' } }\nconsole.log(get(obj, 'a.b.c')); //=> { d: 'foo' }\nconsole.log(get(obj, 'a.b.c.d')); //=> 'foo'\n```\n\n### Supports keys with dots\n\nUnlike other dot-prop libraries, get-value works when keys have dots in them:\n\n```js\nconsole.log(get({ 'a.b': { c: 'd' } }, 'a.b.c'));\n//=> 'd'\n\nconsole.log(get({ 'a.b': { c: { 'd.e': 'f' } } }, 'a.b.c.d.e'));\n//=> 'f'\n```\n\n### Supports arrays\n\n```js\nconsole.log(get({ a: { b: { c: { d: 'foo' } } }, e: [{ f: 'g' }, { f: 'h' }] }, 'e.1.f')); \n//=> 'h'\n\nconsole.log(get({ a: { b: [{ c: 'd' }] } }, 'a.b.0.c')); \n//=> 'f'\n\nconsole.log(get({ a: { b: [{ c: 'd' }, { e: 'f' }] } }, 'a.b.1.e'));\n//=> 'f'\n```\n\n### Supports functions\n\n```js\nfunction foo() {}\nfoo.bar = { baz: 'qux' };\n\nconsole.log(get(foo)); \n//=> { [Function: foo] bar: { baz: 'qux' } }\n\nconsole.log(get(foo, 'bar')); \n//=> { baz: 'qux' }\n\nconsole.log(get(foo, 'bar.baz')); \n//=> qux\n```\n\n### Supports passing object path as an array\n\nSlighly improve performance by passing an array of strings to use as object path segments (this is also useful when you need to dynamically build up the path segments):\n\n```js\nconsole.log(get({ a: { b: 'c' } }, ['a', 'b']));\n//=> 'c'\n```\n\n## Options\n\n### options.default\n\n**Type**: `any`\n\n**Default**: `undefined`\n\nThe default value to return when get-value cannot resolve a value from the given object.\n\n```js\nconst obj = { foo: { a: { b: { c: { d: 'e' } } } } };\nconsole.log(get(obj, 'foo.a.b.c.d', { default: true })); //=> 'e'\nconsole.log(get(obj, 'foo.bar.baz', { default: true })); //=> true\nconsole.log(get(obj, 'foo.bar.baz', { default: false })); //=> false\nconsole.log(get(obj, 'foo.bar.baz', { default: null })); //=> null\n\n// you can also pass the default value as the last argument\n// (this is necessary if the default value is an object)\nconsole.log(get(obj, 'foo.a.b.c.d', true)); //=> 'e'\nconsole.log(get(obj, 'foo.bar.baz', true)); //=> true\nconsole.log(get(obj, 'foo.bar.baz', false)); //=> false\nconsole.log(get(obj, 'foo.bar.baz', null)); //=> null\n```\n\n### options.isValid\n\n**Type**: `function`\n\n**Default**: `true`\n\nIf defined, this function is called on each resolved value. Useful if you want to do `.hasOwnProperty` or `Object.prototype.propertyIsEnumerable`.\n\n```js\nconst isEnumerable = Object.prototype.propertyIsEnumerable;\nconst options = {\n isValid: (key, obj) => isEnumerable.call(obj, key)\n};\n\nconst obj = {};\nObject.defineProperty(obj, 'foo', { value: 'bar', enumerable: false });\n\nconsole.log(get(obj, 'foo', options)); //=> undefined\nconsole.log(get({}, 'hasOwnProperty', options)); //=> undefined\nconsole.log(get({}, 'constructor', options)); //=> undefined\n\n// without \"isValid\" check\nconsole.log(get(obj, 'foo', options)); //=> bar\nconsole.log(get({}, 'hasOwnProperty', options)); //=> [Function: hasOwnProperty]\nconsole.log(get({}, 'constructor', options)); //=> [Function: Object]\n```\n\n### options.split\n\n**Type**: `function`\n\n**Default**: `String.split()`\n\nCustom function to use for splitting the string into object path segments.\n\n```js\nconst obj = { 'a.b': { c: { d: 'e' } } };\n\n// example of using a string to split the object path\nconst options = { split: path => path.split('/') };\nconsole.log(get(obj, 'a.b/c/d', options)); //=> 'e'\n\n// example of using a regex to split the object path\n// (removing escaped dots is unnecessary, this is just an example)\nconst options = { split: path => path.split(/\\\\?\\./) };\nconsole.log(get(obj, 'a\\\\.b.c.d', options)); //=> 'e'\n```\n\n### options.separator\n\n**Type**: `string|regex`\n\n**Default**: `.`\n\nThe separator to use for spliting the string (this is probably not needed when `options.split` is used).\n\n```js\nconst obj = { 'a.b': { c: { d: 'e' } } };\n\nconsole.log(get(obj, 'a.b/c/d', { separator: '/' })); \n//=> 'e'\n\nconsole.log(get(obj, 'a\\\\.b.c.d', { separator: /\\\\?\\./ })); \n//=> 'e'\n```\n\n### options.join\n\n**Type**: `function`\n\n**Default**: `Array.join()`\n\nCustomize how the object path is created when iterating over path segments.\n\n```js\nconst obj = { 'a/b': { c: { d: 'e' } } };\nconst options = {\n // when segs === ['a', 'b'] use a \"/\" to join, otherwise use a \".\"\n join: segs => segs.join(segs[0] === 'a' ? '/' : '.')\n};\n\nconsole.log(get(obj, 'a.b.c.d', options));\n//=> 'e'\n```\n\n### options.joinChar\n\n**Type**: `string`\n\n**Default**: `.`\n\nThe character to use when re-joining the string to check for keys with dots in them (this is probably not needed when `options.join` is used). This can be a different value than the separator, since the separator can be a string or regex.\n\n```js\nconst target = { 'a-b': { c: { d: 'e' } } };\nconst options = { joinChar: '-' };\nconsole.log(get(target, 'a.b.c.d', options)); \n//=> 'e'\n```\n\n## Benchmarks\n\n_(benchmarks were run on a MacBook Pro 2.5 GHz Intel Core i7, 16 GB 1600 MHz DDR3)_.\n\nget-value is more reliable and has more features than dot-prop, without sacrificing performance.\n\n```\n# deep (175 bytes)\n dot-prop x 883,166 ops/sec ±0.93% (86 runs sampled)\n get-value x 1,448,928 ops/sec ±1.53% (87 runs sampled)\n getobject x 213,797 ops/sec ±0.85% (90 runs sampled)\n object-path x 184,347 ops/sec ±2.48% (85 runs sampled)\n\n fastest is get-value (by 339% avg)\n\n# root (210 bytes)\n dot-prop x 3,905,828 ops/sec ±1.36% (87 runs sampled)\n get-value x 16,391,934 ops/sec ±1.43% (83 runs sampled)\n getobject x 1,200,021 ops/sec ±1.81% (88 runs sampled)\n object-path x 2,788,494 ops/sec ±1.81% (86 runs sampled)\n\n fastest is get-value (by 623% avg)\n\n# shallow (84 bytes)\n dot-prop x 2,553,558 ops/sec ±0.89% (89 runs sampled)\n get-value x 3,070,159 ops/sec ±0.88% (90 runs sampled)\n getobject x 726,670 ops/sec ±0.81% (86 runs sampled)\n object-path x 922,351 ops/sec ±2.05% (86 runs sampled)\n\n fastest is get-value (by 219% avg)\n\n```\n\n### Running the benchmarks\n\nClone this library into a local directory:\n\n```sh\n$ git clone https://github.com/jonschlinkert/get-value.git\n```\n\nThen install devDependencies and run benchmarks:\n\n```sh\n$ npm install && node benchmark\n```\n\n## Release history\n\n### v3.0.0\n\n* Improved support for escaping. It's no longer necessary to use backslashes to escape keys.\n* Adds `options.default` for defining a default value to return when no value is resolved.\n* Adds `options.isValid` to allow the user to check the object afterEach iteration.\n* Adds `options.separator` for customizing character to split on.\n* Adds `options.split` for customizing how the object path is split.\n* Adds `options.join` for customizing how the object path is joined when iterating over path segments.\n* Adds `options.joinChar` for customizing the join character.\n\n## About\n\n
\nContributing\n\nPull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).\n\n
\n\n
\nRunning Tests\n\nRunning and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:\n\n```sh\n$ npm install && npm test\n```\n\n
\n\n
\nBuilding docs\n\n_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_\n\nTo generate the readme, run the following command:\n\n```sh\n$ npm install -g verbose/verb#dev verb-generate-readme && verb\n```\n\n
\n\n### Related projects\n\nYou might also be interested in these projects:\n\n* [has-any-deep](https://www.npmjs.com/package/has-any-deep): Return true if `key` exists deeply on the given object. | [homepage](https://github.com/jonschlinkert/has-any-deep \"Return true if `key` exists deeply on the given object. \")\n* [has-any](https://www.npmjs.com/package/has-any): Returns true if an object has any of the specified keys. | [homepage](https://github.com/jonschlinkert/has-any \"Returns true if an object has any of the specified keys.\")\n* [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value \"Returns true if a value exists, false if empty. Works with deeply nested values using object paths.\")\n* [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value \"Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.\")\n* [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value \"Delete nested properties from an object using dot notation.\")\n\n### Contributors\n\n| **Commits** | **Contributor** | \n| --- | --- |\n| 81 | [jonschlinkert](https://github.com/jonschlinkert) |\n| 2 | [ianwalter](https://github.com/ianwalter) |\n| 1 | [doowb](https://github.com/doowb) |\n\n### Author\n\n**Jon Schlinkert**\n\n* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)\n* [GitHub Profile](https://github.com/jonschlinkert)\n* [Twitter Profile](https://twitter.com/jonschlinkert)\n\n### License\n\nCopyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).\nReleased under the [MIT License](LICENSE).\n\n***\n\n_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on March 07, 2018._", "versions": { "0.1.0": { "name": "get-value", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/jest-worker.json b/workspaces/arborist/test/fixtures/registry-mocks/content/jest-worker.json index 21c9ef2a3d431..6a60be1822186 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/jest-worker.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/jest-worker.json @@ -3727,7 +3727,7 @@ "access": "public" }, "gitHead": "cd98198c9397d8b69c55155d7b224d62ef117a90", - "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const worker = new Worker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## Worker\n\n### Methods\n\nThe returned `Worker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", + "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const worker = new Worker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## Worker\n\n### Methods\n\nThe returned `Worker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve afterAll workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", "readmeFilename": "README.md", "description": "Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.", "bugs": { @@ -3916,7 +3916,7 @@ "access": "public" }, "gitHead": "5cc2ccdacb1b2433581222252e43cb5a1f6861a9", - "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const worker = new Worker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## Worker\n\n### Methods\n\nThe returned `Worker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", + "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const worker = new Worker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## Worker\n\n### Methods\n\nThe returned `Worker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve afterAll workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", "readmeFilename": "README.md", "description": "Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.", "bugs": { @@ -4011,7 +4011,7 @@ "access": "public" }, "gitHead": "79b7ab67c63d3708f9689e25fbc0e8b0094bd019", - "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const worker = new Worker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## Worker\n\n### Methods\n\nThe returned `Worker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", + "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const worker = new Worker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`Worker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## Worker\n\n### Methods\n\nThe returned `Worker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve afterAll workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport Worker from 'jest-worker';\n\nasync function main() {\n const myWorker = new Worker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", "readmeFilename": "README.md", "description": "Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.", "bugs": { @@ -5169,7 +5169,7 @@ "_hasShrinkwrap": false } }, - "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport JestWorker from 'jest-worker';\n\nasync function main() {\n const worker = new JestWorker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`JestWorker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## JestWorker\n\n### Methods\n\nThe returned `JestWorker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport JestWorker from 'jest-worker';\n\nasync function main() {\n const myWorker = new JestWorker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport JestWorker from 'jest-worker';\n\nasync function main() {\n const myWorker = new JestWorker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", + "readme": "# jest-worker\n\nModule for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.\n\nThe module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous.\n\nThe module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it.\n\nThe list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the \"minimal example\" section for a valid one.\n\n## Install\n\n```sh\n$ yarn add jest-worker\n```\n\n## Example\n\nThis example covers the minimal usage:\n\n### File `parent.js`\n\n```javascript\nimport JestWorker from 'jest-worker';\n\nasync function main() {\n const worker = new JestWorker(require.resolve('./Worker'));\n const result = await worker.hello('Alice'); // \"Hello, Alice\"\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function hello(param) {\n return 'Hello, ' + param;\n}\n```\n\n## Experimental worker\n\nNode 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a \"threading API\" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`.\n\nSince `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10.\n\n## API\n\nThe only exposed method is a constructor (`JestWorker`) that is initialized by passing the worker path, plus an options object.\n\n### `workerPath: string` (required)\n\nNode module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one.\n\n### `options: Object` (optional)\n\n#### `exposedMethods: $ReadOnlyArray` (optional)\n\nList of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist.\n\n#### `numWorkers: number` (optional)\n\nAmount of workers to spawn. Defaults to the number of CPUs minus 1.\n\n#### `maxRetries: number` (optional)\n\nMaximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries.\n\n#### `forkOptions: Object` (optional)\n\nAllow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options).\n\n#### `computeWorkerKey: (method: string, ...args: Array) => ?string` (optional)\n\nEvery time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`.\n\nThe callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the \"bound worker usage\" section.\n\nBy default, no process is bound to any worker.\n\n#### `setupArgs: Array` (optional)\n\nThe arguments that will be passed to the `setup` method during initialization.\n\n#### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional)\n\nProvide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads.\n\n#### `enableWorkerThreads: boolean` (optional)\n\n`jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`.\n\n## JestWorker\n\n### Methods\n\nThe returned `JestWorker` instance has all the exposed methods, plus some additional ones to interact with the workers itself:\n\n#### `getStdout(): Readable`\n\nReturns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `getStderr(): Readable`\n\nReturns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`.\n\n#### `end()`\n\nFinishes the workers by killing all workers. No further calls can be done to the `Worker` instance.\n\nReturns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans.\n\n**Note:**\n\n`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution.\n\nConsider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve afterAll workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily.\n\n### Worker IDs\n\nEach worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`.\n\n## Setting up and tearing down the child process\n\nThe child process can define two special methods (both of them can be asynchronous):\n\n- `setup()`: If defined, it's executed before the first call to any method in the child.\n- `teardown()`: If defined, it's executed when the farm ends.\n\n# More examples\n\n## Standard usage\n\nThis example covers the standard usage:\n\n### File `parent.js`\n\n```javascript\nimport JestWorker from 'jest-worker';\n\nasync function main() {\n const myWorker = new JestWorker(require.resolve('./Worker'), {\n exposedMethods: ['foo', 'bar', 'getWorkerId'],\n numWorkers: 4,\n });\n\n console.log(await myWorker.foo('Alice')); // \"Hello from foo: Alice\"\n console.log(await myWorker.bar('Bob')); // \"Hello from bar: Bob\"\n console.log(await myWorker.getWorkerId()); // \"3\" -> this message has sent from the 3rd worker\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nexport function foo(param) {\n return 'Hello from foo: ' + param;\n}\n\nexport function bar(param) {\n return 'Hello from bar: ' + param;\n}\n\nexport function getWorkerId() {\n return process.env.JEST_WORKER_ID;\n}\n```\n\n## Bound worker usage:\n\nThis example covers the usage with a `computeWorkerKey` method:\n\n### File `parent.js`\n\n```javascript\nimport JestWorker from 'jest-worker';\n\nasync function main() {\n const myWorker = new JestWorker(require.resolve('./Worker'), {\n computeWorkerKey: (method, filename) => filename,\n });\n\n // Transform the given file, within the first available worker.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n // Wait a bit.\n await sleep(10000);\n\n // Transform the same file again. Will immediately return because the\n // transformed file is cached in the worker, and `computeWorkerKey` ensures\n // the same worker that processed the file the first time will process it now.\n console.log(await myWorker.transform('/tmp/foo.js'));\n\n const {forceExited} = await myWorker.end();\n if (forceExited) {\n console.error('Workers failed to exit gracefully');\n }\n}\n\nmain();\n```\n\n### File `worker.js`\n\n```javascript\nimport babel from '@babel/core';\n\nconst cache = Object.create(null);\n\nexport function transform(filename) {\n if (cache[filename]) {\n return cache[filename];\n }\n\n // jest-worker can handle both immediate results and thenables. If a\n // thenable is returned, it will be await'ed until it resolves.\n return babel.transformFileAsync(filename).then(result => {\n cache[filename] = result;\n\n return result;\n });\n}\n```\n", "maintainers": [ { "name": "scotthovestadt", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/json-schema-traverse.json b/workspaces/arborist/test/fixtures/registry-mocks/content/json-schema-traverse.json index 746422ab8da30..91e678f621dc6 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/json-schema-traverse.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/json-schema-traverse.json @@ -558,7 +558,7 @@ "_hasShrinkwrap": false } }, - "readme": "# json-schema-traverse\nTraverse JSON Schema passing each schema object to callback\n\n[![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse)\n[![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse)\n[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master)\n\n\n## Install\n\n```\nnpm install json-schema-traverse\n```\n\n\n## Usage\n\n```javascript\nconst traverse = require('json-schema-traverse');\nconst schema = {\n properties: {\n foo: {type: 'string'},\n bar: {type: 'integer'}\n }\n};\n\ntraverse(schema, {cb});\n// cb is called 3 times with:\n// 1. root schema\n// 2. {type: 'string'}\n// 3. {type: 'integer'}\n\n// Or:\n\ntraverse(schema, {cb: {pre, post}});\n// pre is called 3 times with:\n// 1. root schema\n// 2. {type: 'string'}\n// 3. {type: 'integer'}\n//\n// post is called 3 times with:\n// 1. {type: 'string'}\n// 2. {type: 'integer'}\n// 3. root schema\n\n```\n\nCallback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed.\n\nCallback is passed these parameters:\n\n- _schema_: the current schema object\n- _JSON pointer_: from the root schema to the current schema object\n- _root schema_: the schema passed to `traverse` object\n- _parent JSON pointer_: from the root schema to the parent schema object (see below)\n- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.)\n- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema\n- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'`\n\n\n## Traverse objects in all unknown keywords\n\n```javascript\nconst traverse = require('json-schema-traverse');\nconst schema = {\n mySchema: {\n minimum: 1,\n maximum: 2\n }\n};\n\ntraverse(schema, {allKeys: true, cb});\n// cb is called 2 times with:\n// 1. root schema\n// 2. mySchema\n```\n\nWithout option `allKeys: true` callback will be called only with root schema.\n\n\n## Enterprise support\n\njson-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers.\n\n\n## Security contact\n\nTo report a security vulnerability, please use the\n[Tidelift security contact](https://tidelift.com/security).\nTidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues.\n\n\n## License\n\n[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE)\n", + "readme": "# json-schema-traverse\nTraverse JSON Schema passing each schema object to callback\n\n[![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse)\n[![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse)\n[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master)\n\n\n## Install\n\n```\nnpm install json-schema-traverse\n```\n\n\n## Usage\n\n```javascript\nconst traverse = require('json-schema-traverse');\nconst schema = {\n properties: {\n foo: {type: 'string'},\n bar: {type: 'integer'}\n }\n};\n\ntraverse(schema, {cb});\n// cb is called 3 times with:\n// 1. root schema\n// 2. {type: 'string'}\n// 3. {type: 'integer'}\n\n// Or:\n\ntraverse(schema, {cb: {pre, post}});\n// pre is called 3 times with:\n// 1. root schema\n// 2. {type: 'string'}\n// 3. {type: 'integer'}\n//\n// post is called 3 times with:\n// 1. {type: 'string'}\n// 2. {type: 'integer'}\n// 3. root schema\n\n```\n\nCallback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called afterAll child elements have been traversed.\n\nCallback is passed these parameters:\n\n- _schema_: the current schema object\n- _JSON pointer_: from the root schema to the current schema object\n- _root schema_: the schema passed to `traverse` object\n- _parent JSON pointer_: from the root schema to the parent schema object (see below)\n- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.)\n- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema\n- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'`\n\n\n## Traverse objects in all unknown keywords\n\n```javascript\nconst traverse = require('json-schema-traverse');\nconst schema = {\n mySchema: {\n minimum: 1,\n maximum: 2\n }\n};\n\ntraverse(schema, {allKeys: true, cb});\n// cb is called 2 times with:\n// 1. root schema\n// 2. mySchema\n```\n\nWithout option `allKeys: true` callback will be called only with root schema.\n\n\n## Enterprise support\n\njson-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers.\n\n\n## Security contact\n\nTo report a security vulnerability, please use the\n[Tidelift security contact](https://tidelift.com/security).\nTidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues.\n\n\n## License\n\n[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE)\n", "maintainers": [ { "name": "esp", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/node-fetch.json b/workspaces/arborist/test/fixtures/registry-mocks/content/node-fetch.json index aacb959060184..5f0a2be10e1ac 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/node-fetch.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/node-fetch.json @@ -3938,7 +3938,7 @@ "instrument": false }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n[![Backers][opencollective-image]][opencollective-url]\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nconst {createWriteStream} = require('fs');\nconst fetch = require('node-fetch');\n\nfetch(\n\t'https://octodex.github.com/images/Fintechtocat.png'\n).then(res => {\n\tconst dest = fs.createWriteStream('./octocat.png');\n\tres.body.pipe(dest);\n});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n[![Backers][opencollective-image]][opencollective-url]\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nconst {createWriteStream} = require('fs');\nconst fetch = require('node-fetch');\n\nfetch(\n\t'https://octodex.github.com/images/Fintechtocat.png'\n).then(res => {\n\tconst dest = fs.createWriteStream('./octocat.png');\n\tres.body.pipe(dest);\n});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "0959ca9739850bbd24e0721cc1296e7a0aa5c2bd", "_id": "node-fetch@3.0.0-beta.1", @@ -4310,7 +4310,7 @@ "instrument": false }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nconst {createWriteStream} = require('fs');\nconst fetch = require('node-fetch');\n\nfetch(\n\t'https://octodex.github.com/images/Fintechtocat.png'\n).then(res => {\n\tconst dest = fs.createWriteStream('./octocat.png');\n\tres.body.pipe(dest);\n});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nconst {createWriteStream} = require('fs');\nconst fetch = require('node-fetch');\n\nfetch(\n\t'https://octodex.github.com/images/Fintechtocat.png'\n).then(res => {\n\tconst dest = fs.createWriteStream('./octocat.png');\n\tres.body.pipe(dest);\n});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "6f2a5efbb6b6177b3ae4a99573b517b4c64cf84a", "_id": "node-fetch@3.0.0-beta.3", @@ -4478,7 +4478,7 @@ "instrument": false }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nconst {createWriteStream} = require('fs');\nconst fetch = require('node-fetch');\n\nfetch(\n\t'https://octodex.github.com/images/Fintechtocat.png'\n).then(res => {\n\tconst dest = fs.createWriteStream('./octocat.png');\n\tres.body.pipe(dest);\n});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nconst {createWriteStream} = require('fs');\nconst fetch = require('node-fetch');\n\nfetch(\n\t'https://octodex.github.com/images/Fintechtocat.png'\n).then(res => {\n\tconst dest = fs.createWriteStream('./octocat.png');\n\tres.body.pipe(dest);\n});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "d75bed0da1d79049426bb0c6fcb5710ae1034a2d", "_id": "node-fetch@3.0.0-beta.4", @@ -4646,7 +4646,7 @@ "extends": "@istanbuljs/nyc-config-babel" }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n - [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n\t.then(res => {\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`unexpected response ${res.statusText}`);\n\t\t}\n\n\t\treturn streamPipeline(res.body, fs.createWriteStream('./octocat.png'));\n\t});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n - [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Default Headers](#default-headers)\n - [Custom Agent](#custom-agent)\n - [Custom highWaterMark](#custom-highwatermark)\n - [Class: Request](#class-request)\n - [new Request(input[, options])](#new-requestinput-options)\n - [Class: Response](#class-response)\n - [new Response([body[, options]])](#new-responsebody-options)\n - [response.ok](#responseok)\n - [response.redirected](#responseredirected)\n - [Class: Headers](#class-headers)\n - [new Headers([init])](#new-headersinit)\n - [Interface: Body](#interface-body)\n - [body.body](#bodybody)\n - [body.bodyUsed](#bodybodyused)\n - [body.arrayBuffer()](#bodyarraybuffer)\n - [body.blob()](#bodyblob)\n - [body.json()](#bodyjson)\n - [body.text()](#bodytext)\n - [body.buffer()](#bodybuffer)\n - [Class: FetchError](#class-fetcherror)\n - [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n - [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of node earlier than 12.x, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis):\n\n```js\n(function() {\n\tif (typeof globalThis === 'object') return;\n\tObject.defineProperty(Object.prototype, '__magic__', {\n\t\tget: function() {\n\t\t\treturn this;\n\t\t},\n\t\tconfigurable: true\n\t});\n\t__magic__.globalThis = __magic__;\n\tdelete Object.prototype.__magic__;\n}());\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body));\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'})\n\t.then(res => res.json()) // expecting a json response\n\t.then(json => console.log(json));\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nfetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: params})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nAdding a catch to the fetch promise chain will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://domain.invalid/').catch(err => console.error(err));\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nfunction checkStatus(res) {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\nfetch('https://httpbin.org/status/400')\n\t.then(checkStatus)\n\t.then(res => console.log('will not get here...'));\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n\t.then(res => {\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`unexpected response ${res.statusText}`);\n\t\t}\n\n\t\treturn streamPipeline(res.body, fs.createWriteStream('./octocat.png'));\n\t});\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\nfetch('https://octodex.github.com/images/Fintechtocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => {\n\t\tconsole.log(type);\n\t});\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://github.com/').then(res => {\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n});\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\t// returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n});\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: stream})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\nfetch('https://httpbin.org/post', options)\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\nfetch('https://example.com', {signal: controller.signal})\n\t.then(res => res.json())\n\t.then(\n\t\tdata => {\n\t\t\tuseData(data);\n\t\t},\n\t\terr => {\n\t\t\tif (err.name === 'AbortError') {\n console.log('request was aborted');\n\t\t\t}\n\t\t}\n\t)\n\t.finally(() => {\n\t\tclearTimeout(timeout);\n\t});\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/test.js) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | -------------------------------------------------------- |\n| `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch (+https://github.com/node-fetch/node-fetch)` |\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16Kb, aka `highWaterMark`) from client-side browsers (>1Mb, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com').then(res => {\n\tconst r1 = res.clone();\n\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n});\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\nfetch('https://example.com', {highWaterMark: 10}).then(res => res.clone().buffer());\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\nSince `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n[![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m)\n---|---|---|---|---\n[David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m)\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\nMIT\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "4f73c8a766fb509fdb27f38bf7ecf3fef9944b4d", "_id": "node-fetch@3.0.0-beta.5", @@ -4812,7 +4812,7 @@ ] }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(res.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${res.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(res.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${res.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "aab3c605eb8e1897dbcf105c43b00d31db754a4d", "_id": "node-fetch@3.0.0-beta.6", @@ -4978,7 +4978,7 @@ ] }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(res.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${res.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise, but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n\n```js\nconst fetch = require('node-fetch');\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(res.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${res.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(res.ok);\n\tconsole.log(res.status);\n\tconsole.log(res.statusText);\n\tconsole.log(res.headers.raw());\n\tconsole.log(res.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(res.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384 // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst Headers = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "9b28c86d965c34bd4b412635c65819ef2a5339ca", "_id": "node-fetch@3.0.0-beta.6-exportfix", @@ -5159,7 +5159,7 @@ ] }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(response.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${response.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(response.ok);\n\tconsole.log(response.status);\n\tconsole.log(response.statusText);\n\tconsole.log(response.headers.raw());\n\tconsole.log(response.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(response.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [formdata-node](https://github.com/octet-stream/form-data):\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('formdata-node');\n\nconst form = new FormData();\nform.set('greeting', 'Hello, world!');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n insecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst { Headers } = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings window.fetch to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(response.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${response.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(response.ok);\n\tconsole.log(response.status);\n\tconsole.log(response.statusText);\n\tconsole.log(response.headers.raw());\n\tconsole.log(response.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(response.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [formdata-node](https://github.com/octet-stream/form-data):\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('formdata-node');\n\nconst form = new FormData();\nform.set('greeting', 'Hello, world!');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n insecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst { Headers } = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "2c005872ae21eff6b11c9536a55e7b8091b96273", "_id": "node-fetch@3.0.0-beta.7", @@ -5338,7 +5338,7 @@ }, "runkitExampleFilename": "example.js", "gitHead": "4083ce5cddbf901ea74a18b8afc630aa45197b83", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings Fetch API to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t\t- [Insecure HTTP Parser](#insecure-http-parser)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(response.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${response.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(response.ok);\n\tconsole.log(response.status);\n\tconsole.log(response.statusText);\n\tconsole.log(response.headers.raw());\n\tconsole.log(response.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(response.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [formdata-node](https://github.com/octet-stream/form-data):\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('formdata-node');\n\nconst form = new FormData();\nform.set('greeting', 'Hello, world!');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n insecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst { Headers } = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings Fetch API to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t\t- [Insecure HTTP Parser](#insecure-http-parser)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(response.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${response.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(response.ok);\n\tconsole.log(response.status);\n\tconsole.log(response.statusText);\n\tconsole.log(response.headers.raw());\n\tconsole.log(response.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(response.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [formdata-node](https://github.com/octet-stream/form-data):\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('formdata-node');\n\nconst form = new FormData();\nform.set('greeting', 'Hello, world!');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n insecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst { Headers } = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "_id": "node-fetch@3.0.0-beta.8", "_nodeVersion": "10.19.0", @@ -5515,7 +5515,7 @@ ] }, "runkitExampleFilename": "example.js", - "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings Fetch API to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t\t- [Insecure HTTP Parser](#insecure-http-parser)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(response.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${response.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(response.ok);\n\tconsole.log(response.status);\n\tconsole.log(response.statusText);\n\tconsole.log(response.headers.raw());\n\tconsole.log(response.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(response.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [formdata-node](https://github.com/octet-stream/form-data):\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('formdata-node');\n\nconst form = new FormData();\nform.set('greeting', 'Hello, world!');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n insecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst { Headers } = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", + "readme": "
\n \t\"Node\n \t
\n \t

A light-weight module that brings Fetch API to Node.js.

\n\t\"Build\n\t\"Coverage\n\t\"Current\n\t\"Install\n\t\"Mentioned\n\t\"Discord\"\n\t
\n\t
\n\tConsider supporting us on our Open Collective:\n\t
\n\t
\n\t\"Open\n
\n\n---\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Buffer](#buffer)\n\t- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file stream](#post-data-using-a-file-stream)\n\t- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t\t- [Insecure HTTP Parser](#insecure-http-parser)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t\t- [body.buffer()](#bodybuffer)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\n\n```js\n// CommonJS\nconst fetch = require('node-fetch');\n\n// ES Module\nimport fetch from 'node-fetch';\n```\n\nIf you want to patch the global object in node:\n\n```js\nconst fetch = require('node-fetch');\n\nif (!globalThis.fetch) {\n globalThis.fetch = fetch;\n}\n```\n\nFor versions of Node earlier than 12, use this `globalThis` [polyfill](https://mathiasbynens.be/notes/globalthis).\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](docs/CHANGELOG.md)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\tconst body = await response.text();\n\n\tconsole.log(body);\n})();\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://api.github.com/users/github');\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst body = {a: 1};\n\n\tconst response = await fetch('https://httpbin.org/post', {\n\t\tmethod: 'post',\n\t\tbody: JSON.stringify(body),\n\t\theaders: {'Content-Type': 'application/json'}\n\t});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst fetch = require('node-fetch');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\n\tconst json = await response.json();\n\n\tconsole.log(json);\n})();\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nconst fetch = require('node-fetch');\n\ntry {\n\tfetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nconst fetch = require('node-fetch');\n\nconst checkStatus = res => {\n\tif (res.ok) {\n\t\t// res.status >= 200 && res.status < 300\n\t\treturn res;\n\t} else {\n\t\tthrow MyCustomError(res.statusText);\n\t}\n}\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/status/400');\n\tconst data = checkStatus(response);\n\n\tconsole.log(data); //=> MyCustomError\n})();\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nconst util = require('util');\nconst fs = require('fs');\nconst streamPipeline = util.promisify(require('stream').pipeline);\n\n(async () => {\n\tconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\t\n\tif (response.ok) {\n\t\treturn streamPipeline(response.body, fs.createWriteStream('./octocat.png'));\n\t}\n\n\tthrow new Error(`unexpected response ${response.statusText}`);\n})();\n```\n\n### Buffer\n\nIf you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a `node-fetch` only API)\n\n```js\nconst fetch = require('node-fetch');\nconst fileType = require('file-type');\n\n(async () => {\n\tconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\n\tconst buffer = await response.buffer();\n\tconst type = fileType.fromBuffer(buffer)\n\t\n\tconsole.log(type);\n})();\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://github.com/');\n\t\n\tconsole.log(response.ok);\n\tconsole.log(response.status);\n\tconsole.log(response.statusText);\n\tconsole.log(response.headers.raw());\n\tconsole.log(response.headers.get('content-type'));\n})();\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\t\n\t// Returns an array of values, instead of a string of comma-separated values\n\tconsole.log(response.headers.raw()['set-cookie']);\n})();\n```\n\n### Post data using a file stream\n\n```js\nconst {createReadStream} = require('fs');\nconst fetch = require('node-fetch');\n\nconst stream = createReadStream('input.txt');\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\n### Post with form-data (detect multipart)\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst options = {\n\tmethod: 'POST',\n\tbody: form,\n\theaders: form.getHeaders()\n};\n\n(async () => {\n\tconst response = await fetch('https://httpbin.org/post', options);\n\tconst json = await response.json();\n\t\n\tconsole.log(json)\n})();\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [formdata-node](https://github.com/octet-stream/form-data):\n\n```js\nconst fetch = require('node-fetch');\nconst FormData = require('formdata-node');\n\nconst form = new FormData();\nform.set('greeting', 'Hello, world!');\n\nfetch('https://httpbin.org/post', {method: 'POST', body: form})\n\t.then(res => res.json())\n\t.then(json => console.log(json));\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nconst fetch = require('node-fetch');\nconst AbortController = require('abort-controller');\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() => {\n\tcontroller.abort();\n}, 150);\n\n(async () => {\n\ttry {\n\t\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\t\tconst data = await response.json();\n\t\t\n\t\tuseData(data);\n\t} catch (error) {\n\t\tif (error.name === 'AbortError') {\n console.log('request was aborted');\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n})();\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // Set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // Pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null, // http(s).Agent instance or function that returns an instance (see below)\n highWaterMark: 16384, // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n insecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header | Value |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding` | `gzip,deflate,br` _(when `options.compress === true`)_ |\n| `Accept` | `*/*` |\n| `Connection` | `close` _(when no `options.agent` is present)_ |\n| `Content-Length` | _(automatically calculated, if possible)_ |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ |\n| `User-Agent` | `node-fetch` |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst http = require('http');\nconst https = require('https');\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com');\n\tconst r1 = await response.clone();\n\t\n\treturn Promise.all([res.json(), r1.text()]).then(results => {\n\t\tconsole.log(results[0]);\n\t\tconsole.log(results[1]);\n\t});\n})();\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nconst fetch = require('node-fetch');\n\n(async () => {\n\tconst response = await fetch('https://example.com', {\n\t\t// About 1MB\n\t\thighWaterMark: 1024 * 1024\n\t});\n\t\n\treturn res.clone().buffer();\n})();\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n_(spec-compliant)_\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n_(spec-compliant)_\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n_(spec-compliant)_\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n_(spec-compliant)_\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n_(spec-compliant)_\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nconst { Headers } = require('node-fetch');\n\nconst meta = {\n\t'Content-Type': 'text/xml',\n\t'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n_(deviation from spec)_\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n_(spec-compliant)_\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n_(spec-compliant)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n_(node-fetch extension)_\n\n- Returns: `Promise`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n\n\n### Class: FetchError\n\n_(node-fetch extension)_\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n\n### Class: AbortError\n\n_(node-fetch extension)_\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\n$ npm install --save-dev @types/node-fetch\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/) | [Jimmy Wärting](https://jimmy.warting.se/) | [Antoni Kepinski](https://kepinski.me) | [Richie Bendall](https://www.richie-bendall.ml/) | [Gregor Martynus](https://twitter.com/gr2m) |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n", "readmeFilename": "README.md", "gitHead": "38839c53bd417cef440757265f75c8371d4c51e6", "_id": "node-fetch@3.0.0-beta.9", @@ -5661,7 +5661,7 @@ "_hasShrinkwrap": false } }, - "readme": "node-fetch\n==========\n\n[![npm version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![coverage status][codecov-image]][codecov-url]\n[![install size][install-size-image]][install-size-url]\n[![Discord][discord-image]][discord-url]\n\nA light-weight module that brings `window.fetch` to Node.js\n\n(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567))\n\n[![Backers][opencollective-image]][opencollective-url]\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Class: Request](#class-request)\n - [Class: Response](#class-response)\n - [Class: Headers](#class-headers)\n - [Interface: Body](#interface-body)\n - [Class: FetchError](#class-fetcherror)\n- [License](#license)\n- [Acknowledgement](#acknowledgement)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body on both request and response.\n- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.\n\n## Difference from client-side fetch\n\n- See [Known Differences](LIMITS.md) for details.\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`2.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\nWe suggest you load the module via `require` until the stabilization of ES modules in node:\n```js\nconst fetch = require('node-fetch');\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n```js\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.\n\n#### Plain text or HTML\n```js\nfetch('https://github.com/')\n .then(res => res.text())\n .then(body => console.log(body));\n```\n\n#### JSON\n\n```js\n\nfetch('https://api.github.com/users/github')\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Simple Post\n```js\nfetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })\n .then(res => res.json()) // expecting a json response\n .then(json => console.log(json));\n```\n\n#### Post with JSON\n\n```js\nconst body = { a: 1 };\n\nfetch('https://httpbin.org/post', {\n method: 'post',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' },\n })\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Post with form parameters\n`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst { URLSearchParams } = require('url');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', { method: 'POST', body: params })\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Handling exceptions\nNOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information.\n\nAdding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.\n\n```js\nfetch('https://domain.invalid/')\n .catch(err => console.error(err));\n```\n\n#### Handling client and server errors\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nfunction checkStatus(res) {\n if (res.ok) { // res.status >= 200 && res.status < 300\n return res;\n } else {\n throw MyCustomError(res.statusText);\n }\n}\n\nfetch('https://httpbin.org/status/400')\n .then(checkStatus)\n .then(res => console.log('will not get here...'))\n```\n\n## Advanced Usage\n\n#### Streams\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n .then(res => {\n const dest = fs.createWriteStream('./octocat.png');\n res.body.pipe(dest);\n });\n```\n\n#### Buffer\nIf you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)\n\n```js\nconst fileType = require('file-type');\n\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n .then(res => res.buffer())\n .then(buffer => fileType(buffer))\n .then(type => { /* ... */ });\n```\n\n#### Accessing Headers and other Meta data\n```js\nfetch('https://github.com/')\n .then(res => {\n console.log(res.ok);\n console.log(res.status);\n console.log(res.statusText);\n console.log(res.headers.raw());\n console.log(res.headers.get('content-type'));\n });\n```\n\n#### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nfetch(url).then(res => {\n // returns an array of values, instead of a string of comma-separated values\n console.log(res.headers.raw()['set-cookie']);\n});\n```\n\n#### Post data using a file stream\n\n```js\nconst { createReadStream } = require('fs');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', { method: 'POST', body: stream })\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Post with form-data (detect multipart)\n\n```js\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', { method: 'POST', body: form })\n .then(res => res.json())\n .then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst form = new FormData();\nform.append('a', 1);\n\nconst options = {\n method: 'POST',\n body: form,\n headers: form.getHeaders()\n}\n\nfetch('https://httpbin.org/post', options)\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Request cancellation with AbortSignal\n\n> NOTE: You may cancel streamed requests only on Node >= v8.0.0\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nimport AbortController from 'abort-controller';\n\nconst controller = new AbortController();\nconst timeout = setTimeout(\n () => { controller.abort(); },\n 150,\n);\n\nfetch(url, { signal: controller.signal })\n .then(res => res.json())\n .then(\n data => {\n useData(data)\n },\n err => {\n if (err.name === 'AbortError') {\n // request was aborted\n }\n },\n )\n .finally(() => {\n clearTimeout(timeout);\n });\n```\n\nSee [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.\n\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null // http(s).Agent instance or function that returns an instance (see below)\n}\n```\n\n##### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\nHeader | Value\n------------------- | --------------------------------------------------------\n`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_\n`Accept` | `*/*`\n`Connection` | `close` _(when no `options.agent` is present)_\n`Content-Length` | _(automatically calculated, if possible)_\n`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_\n`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)`\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n##### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst httpAgent = new http.Agent({\n keepAlive: true\n});\nconst httpsAgent = new https.Agent({\n keepAlive: true\n});\n\nconst options = {\n agent: function (_parsedURL) {\n if (_parsedURL.protocol == 'http:') {\n return httpAgent;\n } else {\n return httpsAgent;\n }\n }\n}\n```\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n*(spec-compliant)*\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n*(spec-compliant)*\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n*(spec-compliant)*\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n*(spec-compliant)*\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n*(spec-compliant)*\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\n\nconst meta = {\n 'Content-Type': 'text/xml',\n 'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [\n [ 'Content-Type', 'text/xml' ],\n [ 'Breaking-Bad', '<3' ]\n];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n*(deviation from spec)*\n\n* Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n*(spec-compliant)*\n\n* `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n#### body.blob()\n#### body.json()\n#### body.text()\n\n*(spec-compliant)*\n\n* Returns: Promise\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n*(node-fetch extension)*\n\n* Returns: Promise<Buffer>\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n#### body.textConverted()\n\n*(node-fetch extension)*\n\n* Returns: Promise<String>\n\nIdentical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible.\n\n(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.)\n\n\n### Class: FetchError\n\n*(node-fetch extension)*\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n### Class: AbortError\n\n*(node-fetch extension)*\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr).\n\n## License\n\nMIT\n\n[npm-image]: https://flat.badgen.net/npm/v/node-fetch\n[npm-url]: https://www.npmjs.com/package/node-fetch\n[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch\n[travis-url]: https://travis-ci.org/bitinn/node-fetch\n[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master\n[codecov-url]: https://codecov.io/gh/bitinn/node-fetch\n[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch\n[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch\n[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square\n[discord-url]: https://discord.gg/Zxbndcm\n[opencollective-image]: https://opencollective.com/node-fetch/backers.svg\n[opencollective-url]: https://opencollective.com/node-fetch\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md\n[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md\n[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md\n", + "readme": "node-fetch\n==========\n\n[![npm version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![coverage status][codecov-image]][codecov-url]\n[![install size][install-size-image]][install-size-url]\n[![Discord][discord-image]][discord-url]\n\nA light-weight module that brings `window.fetch` to Node.js\n\n(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567))\n\n[![Backers][opencollective-image]][opencollective-url]\n\n\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Common Usage](#common-usage)\n - [Plain text or HTML](#plain-text-or-html)\n - [JSON](#json)\n - [Simple Post](#simple-post)\n - [Post with JSON](#post-with-json)\n - [Post with form parameters](#post-with-form-parameters)\n - [Handling exceptions](#handling-exceptions)\n - [Handling client and server errors](#handling-client-and-server-errors)\n- [Advanced Usage](#advanced-usage)\n - [Streams](#streams)\n - [Buffer](#buffer)\n - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)\n - [Extract Set-Cookie Header](#extract-set-cookie-header)\n - [Post data using a file stream](#post-data-using-a-file-stream)\n - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)\n - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n - [fetch(url[, options])](#fetchurl-options)\n - [Options](#options)\n - [Class: Request](#class-request)\n - [Class: Response](#class-response)\n - [Class: Headers](#class-headers)\n - [Interface: Body](#interface-body)\n - [Class: FetchError](#class-fetcherror)\n- [License](#license)\n- [Acknowledgement](#acknowledgement)\n\n\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise but allow substituting it with [insert your favorite promise library].\n- Use native Node streams for body on both request and response.\n- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.\n\n## Difference from client-side fetch\n\n- See [Known Differences](LIMITS.md) for details.\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`2.x`)\n\n```sh\n$ npm install node-fetch\n```\n\n## Loading and configuring the module\nWe suggest you load the module via `require` until the stabilization of ES modules in node:\n```js\nconst fetch = require('node-fetch');\n```\n\nIf you are using a Promise library other than native, set it through `fetch.Promise`:\n```js\nconst Bluebird = require('bluebird');\n\nfetch.Promise = Bluebird;\n```\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.\n\n#### Plain text or HTML\n```js\nfetch('https://github.com/')\n .then(res => res.text())\n .then(body => console.log(body));\n```\n\n#### JSON\n\n```js\n\nfetch('https://api.github.com/users/github')\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Simple Post\n```js\nfetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })\n .then(res => res.json()) // expecting a json response\n .then(json => console.log(json));\n```\n\n#### Post with JSON\n\n```js\nconst body = { a: 1 };\n\nfetch('https://httpbin.org/post', {\n method: 'post',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' },\n })\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Post with form parameters\n`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nconst { URLSearchParams } = require('url');\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nfetch('https://httpbin.org/post', { method: 'POST', body: params })\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Handling exceptions\nNOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information.\n\nAdding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.\n\n```js\nfetch('https://domain.invalid/')\n .catch(err => console.error(err));\n```\n\n#### Handling client and server errors\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nfunction checkStatus(res) {\n if (res.ok) { // res.status >= 200 && res.status < 300\n return res;\n } else {\n throw MyCustomError(res.statusText);\n }\n}\n\nfetch('https://httpbin.org/status/400')\n .then(checkStatus)\n .then(res => console.log('will not get here...'))\n```\n\n## Advanced Usage\n\n#### Streams\nThe \"Node.js way\" is to use streams when possible:\n\n```js\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n .then(res => {\n const dest = fs.createWriteStream('./octocat.png');\n res.body.pipe(dest);\n });\n```\n\n#### Buffer\nIf you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)\n\n```js\nconst fileType = require('file-type');\n\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n .then(res => res.buffer())\n .then(buffer => fileType(buffer))\n .then(type => { /* ... */ });\n```\n\n#### Accessing Headers and other Meta data\n```js\nfetch('https://github.com/')\n .then(res => {\n console.log(res.ok);\n console.log(res.status);\n console.log(res.statusText);\n console.log(res.headers.raw());\n console.log(res.headers.get('content-type'));\n });\n```\n\n#### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nfetch(url).then(res => {\n // returns an array of values, instead of a string of comma-separated values\n console.log(res.headers.raw()['set-cookie']);\n});\n```\n\n#### Post data using a file stream\n\n```js\nconst { createReadStream } = require('fs');\n\nconst stream = createReadStream('input.txt');\n\nfetch('https://httpbin.org/post', { method: 'POST', body: stream })\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Post with form-data (detect multipart)\n\n```js\nconst FormData = require('form-data');\n\nconst form = new FormData();\nform.append('a', 1);\n\nfetch('https://httpbin.org/post', { method: 'POST', body: form })\n .then(res => res.json())\n .then(json => console.log(json));\n\n// OR, using custom headers\n// NOTE: getHeaders() is non-standard API\n\nconst form = new FormData();\nform.append('a', 1);\n\nconst options = {\n method: 'POST',\n body: form,\n headers: form.getHeaders()\n}\n\nfetch('https://httpbin.org/post', options)\n .then(res => res.json())\n .then(json => console.log(json));\n```\n\n#### Request cancellation with AbortSignal\n\n> NOTE: You may cancel streamed requests only on Node >= v8.0.0\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nimport AbortController from 'abort-controller';\n\nconst controller = new AbortController();\nconst timeout = setTimeout(\n () => { controller.abort(); },\n 150,\n);\n\nfetch(url, { signal: controller.signal })\n .then(res => res.json())\n .then(\n data => {\n useData(data)\n },\n err => {\n if (err.name === 'AbortError') {\n // request was aborted\n }\n },\n )\n .finally(() => {\n clearTimeout(timeout);\n });\n```\n\nSee [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.\n\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: Promise<[Response](#class-response)>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\n### Options\n\nThe default values are shown afterEach option key.\n\n```js\n{\n // These properties are part of the Fetch Standard\n method: 'GET',\n headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)\n body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect\n signal: null, // pass an instance of AbortSignal to optionally abort requests\n\n // The following properties are node-fetch extensions\n follow: 20, // maximum redirect count. 0 to not follow redirect\n timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.\n compress: true, // support gzip/deflate content encoding. false to disable\n size: 0, // maximum response body size in bytes. 0 to disable\n agent: null // http(s).Agent instance or function that returns an instance (see below)\n}\n```\n\n##### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\nHeader | Value\n------------------- | --------------------------------------------------------\n`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_\n`Accept` | `*/*`\n`Connection` | `close` _(when no `options.agent` is present)_\n`Content-Length` | _(automatically calculated, if possible)_\n`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_\n`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)`\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n##### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nconst httpAgent = new http.Agent({\n keepAlive: true\n});\nconst httpsAgent = new https.Agent({\n keepAlive: true\n});\n\nconst options = {\n agent: function (_parsedURL) {\n if (_parsedURL.protocol == 'http:') {\n return httpAgent;\n } else {\n return httpsAgent;\n }\n }\n}\n```\n\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n*(spec-compliant)*\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `trailer`\n\n#### new Response([body[, options]])\n\n*(spec-compliant)*\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n*(spec-compliant)*\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n*(spec-compliant)*\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n*(spec-compliant)*\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\n\nconst meta = {\n 'Content-Type': 'text/xml',\n 'Breaking-Bad': '<3'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [\n [ 'Content-Type', 'text/xml' ],\n [ 'Breaking-Bad', '<3' ]\n];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nmeta.set('Breaking-Bad', '<3');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in node-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n*(deviation from spec)*\n\n* Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n*(spec-compliant)*\n\n* `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n#### body.blob()\n#### body.json()\n#### body.text()\n\n*(spec-compliant)*\n\n* Returns: Promise\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n*(node-fetch extension)*\n\n* Returns: Promise<Buffer>\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n#### body.textConverted()\n\n*(node-fetch extension)*\n\n* Returns: Promise<String>\n\nIdentical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible.\n\n(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.)\n\n\n### Class: FetchError\n\n*(node-fetch extension)*\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\n### Class: AbortError\n\n*(node-fetch extension)*\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr).\n\n## License\n\nMIT\n\n[npm-image]: https://flat.badgen.net/npm/v/node-fetch\n[npm-url]: https://www.npmjs.com/package/node-fetch\n[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch\n[travis-url]: https://travis-ci.org/bitinn/node-fetch\n[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master\n[codecov-url]: https://codecov.io/gh/bitinn/node-fetch\n[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch\n[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch\n[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square\n[discord-url]: https://discord.gg/Zxbndcm\n[opencollective-image]: https://opencollective.com/node-fetch/backers.svg\n[opencollective-url]: https://opencollective.com/node-fetch\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md\n[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md\n[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md\n", "maintainers": [ { "email": "xxczaki@pm.me", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/performance-now.json b/workspaces/arborist/test/fixtures/registry-mocks/content/performance-now.json index b90b92eec69ea..c3eb0557d66a2 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/performance-now.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/performance-now.json @@ -621,7 +621,7 @@ "directories": {} } }, - "readme": "# performance-now [![Build Status](https://travis-ci.org/braveg1rl/performance-now.png?branch=master)](https://travis-ci.org/braveg1rl/performance-now) [![Dependency Status](https://david-dm.org/braveg1rl/performance-now.png)](https://david-dm.org/braveg1rl/performance-now)\n\nImplements a function similar to `performance.now` (based on `process.hrtime`).\n\nModern browsers have a `window.performance` object with - among others - a `now` method which gives time in milliseconds, but with sub-millisecond precision. This module offers the same function based on the Node.js native `process.hrtime` function.\n\nUsing `process.hrtime` means that the reported time will be monotonically increasing, and not subject to clock-drift.\n\nAccording to the [High Resolution Time specification](http://www.w3.org/TR/hr-time/), the number of milliseconds reported by `performance.now` should be relative to the value of `performance.timing.navigationStart`.\n\nIn the current version of the module (2.0) the reported time is relative to the time the current Node process has started (inferred from `process.uptime()`).\n\nVersion 1.0 reported a different time. The reported time was relative to the time the module was loaded (i.e. the time it was first `require`d). If you need this functionality, version 1.0 is still available on NPM.\n\n## Example usage\n\n```javascript\nvar now = require(\"performance-now\")\nvar start = now()\nvar end = now()\nconsole.log(start.toFixed(3)) // the number of milliseconds the current node process is running\nconsole.log((start-end).toFixed(3)) // ~ 0.002 on my system\n```\n\nRunning the now function two times right after each other yields a time difference of a few microseconds. Given this overhead, I think it's best to assume that the precision of intervals computed with this method is not higher than 10 microseconds, if you don't know the exact overhead on your own system.\n\n## License\n\nperformance-now is released under the [MIT License](http://opensource.org/licenses/MIT).\nCopyright (c) 2017 Braveg1rl\n", + "readme": "# performance-now [![Build Status](https://travis-ci.org/braveg1rl/performance-now.png?branch=master)](https://travis-ci.org/braveg1rl/performance-now) [![Dependency Status](https://david-dm.org/braveg1rl/performance-now.png)](https://david-dm.org/braveg1rl/performance-now)\n\nImplements a function similar to `performance.now` (based on `process.hrtime`).\n\nModern browsers have a `window.performance` object with - among others - a `now` method which gives time in milliseconds, but with sub-millisecond precision. This module offers the same function based on the Node.js native `process.hrtime` function.\n\nUsing `process.hrtime` means that the reported time will be monotonically increasing, and not subject to clock-drift.\n\nAccording to the [High Resolution Time specification](http://www.w3.org/TR/hr-time/), the number of milliseconds reported by `performance.now` should be relative to the value of `performance.timing.navigationStart`.\n\nIn the current version of the module (2.0) the reported time is relative to the time the current Node process has started (inferred from `process.uptime()`).\n\nVersion 1.0 reported a different time. The reported time was relative to the time the module was loaded (i.e. the time it was first `require`d). If you need this functionality, version 1.0 is still available on NPM.\n\n## Example usage\n\n```javascript\nvar now = require(\"performance-now\")\nvar start = now()\nvar end = now()\nconsole.log(start.toFixed(3)) // the number of milliseconds the current node process is running\nconsole.log((start-end).toFixed(3)) // ~ 0.002 on my system\n```\n\nRunning the now function two times right afterEach other yields a time difference of a few microseconds. Given this overhead, I think it's best to assume that the precision of intervals computed with this method is not higher than 10 microseconds, if you don't know the exact overhead on your own system.\n\n## License\n\nperformance-now is released under the [MIT License](http://opensource.org/licenses/MIT).\nCopyright (c) 2017 Braveg1rl\n", "maintainers": [ { "name": "meryn", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/stream-http.json b/workspaces/arborist/test/fixtures/registry-mocks/content/stream-http.json index 08eb09e381723..f00f4d3a8c052 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/stream-http.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/stream-http.json @@ -3025,7 +3025,7 @@ "_hasShrinkwrap": false } }, - "readme": "# stream-http [![Build Status](https://travis-ci.org/jhiesey/stream-http.svg?branch=master)](https://travis-ci.org/jhiesey/stream-http)\n\n[![Sauce Test Status](https://saucelabs.com/browser-matrix/stream-http.svg)](https://saucelabs.com/u/stream-http)\n\nThis module is an implementation of Node's native `http` module for the browser.\nIt tries to match Node's API and behavior as closely as possible, but some features\naren't available, since browsers don't give nearly as much control over requests.\n\nThis is heavily inspired by, and intended to replace, [http-browserify](https://github.com/substack/http-browserify).\n\n## What does it do?\n\nIn accordance with its name, `stream-http` tries to provide data to its caller before\nthe request has completed whenever possible.\n\nBackpressure, allowing the browser to only pull data from the server as fast as it is\nconsumed, is supported in:\n* Chrome >= 58 (using `fetch` and `WritableStream`)\n\nThe following browsers support true streaming, where only a small amount of the request\nhas to be held in memory at once:\n* Chrome >= 43 (using the `fetch` API)\n* Firefox >= 9 (using `moz-chunked-arraybuffer` responseType with xhr)\n\nAll other supported browsers support pseudo-streaming, where the data is available before\nthe request finishes, but the entire response must be held in memory. This works for both\ntext and binary data.\n\n### IE note:\nAs of version 3.0.0, IE10 and below are no longer supported. IE11 support will remain for\nnow.\n\n## How do you use it?\n\nThe intent is to have the same API as the client part of the\n[Node HTTP module](https://nodejs.org/api/http.html). The interfaces are the same wherever\npractical, although limitations in browsers make an exact clone of the Node API impossible.\n\nThis module implements `http.request`, `http.get`, and most of `http.ClientRequest`\nand `http.IncomingMessage` in addition to `http.METHODS` and `http.STATUS_CODES`. See the\nNode docs for how these work.\n\n### Extra features compared to Node\n\n* The `message.url` property provides access to the final URL after all redirects. This\nis useful since the browser follows all redirects silently, unlike Node. It is available\nin Chrome 37 and newer, Firefox 32 and newer, and Safari 9 and newer.\n\n* The `options.withCredentials` boolean flag, used to indicate if the browser should send\ncookies or authentication information with a CORS request. Default false.\n\nThis module has to make some tradeoffs to support binary data and/or streaming. Generally,\nthe module can make a fairly good decision about which underlying browser features to use,\nbut sometimes it helps to get a little input from the developer.\n\n* The `options.mode` field passed into `http.request` or `http.get` can take on one of the\nfollowing values:\n * 'default' (or any falsy value, including `undefined`): Try to provide partial data before\nthe request completes, but not at the cost of correctness for binary data or correctness of\nthe 'content-type' response header. This mode will also avoid slower code paths whenever\npossible, which is particularly useful when making large requests in a browser like Safari\nthat has a weaker JavaScript engine.\n * 'allow-wrong-content-type': Provides partial data in more cases than 'default', but\nat the expense of causing the 'content-type' response header to be incorrectly reported\n(as 'text/plain; charset=x-user-defined') in some browsers, notably Safari and Chrome 42\nand older. Preserves binary data whenever possible. In some cases the implementation may\nalso be a bit slow. This was the default in versions of this module before 1.5.\n * 'prefer-streaming': Provide data before the request completes even if binary data (anything\nthat isn't a single-byte ASCII or UTF8 character) will be corrupted. Of course, this option\nis only safe for text data. May also cause the 'content-type' response header to be\nincorrectly reported (as 'text/plain; charset=x-user-defined').\n * 'disable-fetch': Force the use of plain XHR regardless of the browser declaring a fetch\ncapability. Preserves the correctness of binary data and the 'content-type' response header.\n * 'prefer-fast': Deprecated; now a synonym for 'default', which has the same performance\ncharacteristics as this mode did in versions before 1.5.\n\n* `options.requestTimeout` allows setting a timeout in millisecionds for XHR and fetch (if\nsupported by the browser). This is a limit on how long the entire process takes from\nbeginning to end. Note that this is not the same as the node `setTimeout` functions,\nwhich apply to pauses in data transfer over the underlying socket, or the node `timeout`\noption, which applies to opening the connection.\n\n### Features missing compared to Node\n\n* `http.Agent` is only a stub\n* The 'socket', 'connect', 'upgrade', and 'continue' events on `http.ClientRequest`.\n* Any operations, including `request.setTimeout`, that operate directly on the underlying\nsocket.\n* Any options that are disallowed for security reasons. This includes setting or getting\ncertain headers.\n* `message.httpVersion`\n* `message.rawHeaders` is modified by the browser, and may not quite match what is sent by\nthe server.\n* `message.trailers` and `message.rawTrailers` will remain empty.\n* Redirects are followed silently by the browser, so it isn't possible to access the 301/302\nredirect pages.\n* The `timeout` event/option and `setTimeout` functions, which operate on the underlying\nsocket, are not available. However, see `options.requestTimeout` above.\n\n## Example\n\n``` js\nhttp.get('/bundle.js', function (res) {\n\tvar div = document.getElementById('result');\n\tdiv.innerHTML += 'GET /beep
';\n\n\tres.on('data', function (buf) {\n\t\tdiv.innerHTML += buf;\n\t});\n\n\tres.on('end', function () {\n\t\tdiv.innerHTML += '
__END__';\n\t});\n})\n```\n\n## Running tests\n\nThere are two sets of tests: the tests that run in Node (found in `test/node`) and the tests\nthat run in the browser (found in `test/browser`). Normally the browser tests run on\n[Sauce Labs](http://saucelabs.com/).\n\nRunning `npm test` will run both sets of tests, but in order for the Sauce Labs tests to run\nyou will need to sign up for an account (free for open source projects) and put the\ncredentials in a [`.airtaprc` file](https://github.com/airtap/airtap/blob/master/doc/airtaprc.md).\nYou will also need to run a [Sauce Connect Proxy](https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy)\nwith the same credentials.\n\nTo run just the Node tests, run `npm run test-node`.\n\nTo run the browser tests locally, run `npm run test-browser-local` and point your browser to\nthe link shown in your terminal.\n\n## License\n\nMIT. Copyright (C) John Hiesey and other contributors.\n", + "readme": "# stream-http [![Build Status](https://travis-ci.org/jhiesey/stream-http.svg?branch=master)](https://travis-ci.org/jhiesey/stream-http)\n\n[![Sauce Test Status](https://saucelabs.com/browser-matrix/stream-http.svg)](https://saucelabs.com/u/stream-http)\n\nThis module is an implementation of Node's native `http` module for the browser.\nIt tries to match Node's API and behavior as closely as possible, but some features\naren't available, since browsers don't give nearly as much control over requests.\n\nThis is heavily inspired by, and intended to replace, [http-browserify](https://github.com/substack/http-browserify).\n\n## What does it do?\n\nIn accordance with its name, `stream-http` tries to provide data to its caller before\nthe request has completed whenever possible.\n\nBackpressure, allowing the browser to only pull data from the server as fast as it is\nconsumed, is supported in:\n* Chrome >= 58 (using `fetch` and `WritableStream`)\n\nThe following browsers support true streaming, where only a small amount of the request\nhas to be held in memory at once:\n* Chrome >= 43 (using the `fetch` API)\n* Firefox >= 9 (using `moz-chunked-arraybuffer` responseType with xhr)\n\nAll other supported browsers support pseudo-streaming, where the data is available before\nthe request finishes, but the entire response must be held in memory. This works for both\ntext and binary data.\n\n### IE note:\nAs of version 3.0.0, IE10 and below are no longer supported. IE11 support will remain for\nnow.\n\n## How do you use it?\n\nThe intent is to have the same API as the client part of the\n[Node HTTP module](https://nodejs.org/api/http.html). The interfaces are the same wherever\npractical, although limitations in browsers make an exact clone of the Node API impossible.\n\nThis module implements `http.request`, `http.get`, and most of `http.ClientRequest`\nand `http.IncomingMessage` in addition to `http.METHODS` and `http.STATUS_CODES`. See the\nNode docs for how these work.\n\n### Extra features compared to Node\n\n* The `message.url` property provides access to the final URL afterAll redirects. This\nis useful since the browser follows all redirects silently, unlike Node. It is available\nin Chrome 37 and newer, Firefox 32 and newer, and Safari 9 and newer.\n\n* The `options.withCredentials` boolean flag, used to indicate if the browser should send\ncookies or authentication information with a CORS request. Default false.\n\nThis module has to make some tradeoffs to support binary data and/or streaming. Generally,\nthe module can make a fairly good decision about which underlying browser features to use,\nbut sometimes it helps to get a little input from the developer.\n\n* The `options.mode` field passed into `http.request` or `http.get` can take on one of the\nfollowing values:\n * 'default' (or any falsy value, including `undefined`): Try to provide partial data before\nthe request completes, but not at the cost of correctness for binary data or correctness of\nthe 'content-type' response header. This mode will also avoid slower code paths whenever\npossible, which is particularly useful when making large requests in a browser like Safari\nthat has a weaker JavaScript engine.\n * 'allow-wrong-content-type': Provides partial data in more cases than 'default', but\nat the expense of causing the 'content-type' response header to be incorrectly reported\n(as 'text/plain; charset=x-user-defined') in some browsers, notably Safari and Chrome 42\nand older. Preserves binary data whenever possible. In some cases the implementation may\nalso be a bit slow. This was the default in versions of this module before 1.5.\n * 'prefer-streaming': Provide data before the request completes even if binary data (anything\nthat isn't a single-byte ASCII or UTF8 character) will be corrupted. Of course, this option\nis only safe for text data. May also cause the 'content-type' response header to be\nincorrectly reported (as 'text/plain; charset=x-user-defined').\n * 'disable-fetch': Force the use of plain XHR regardless of the browser declaring a fetch\ncapability. Preserves the correctness of binary data and the 'content-type' response header.\n * 'prefer-fast': Deprecated; now a synonym for 'default', which has the same performance\ncharacteristics as this mode did in versions before 1.5.\n\n* `options.requestTimeout` allows setting a timeout in millisecionds for XHR and fetch (if\nsupported by the browser). This is a limit on how long the entire process takes from\nbeginning to end. Note that this is not the same as the node `setTimeout` functions,\nwhich apply to pauses in data transfer over the underlying socket, or the node `timeout`\noption, which applies to opening the connection.\n\n### Features missing compared to Node\n\n* `http.Agent` is only a stub\n* The 'socket', 'connect', 'upgrade', and 'continue' events on `http.ClientRequest`.\n* Any operations, including `request.setTimeout`, that operate directly on the underlying\nsocket.\n* Any options that are disallowed for security reasons. This includes setting or getting\ncertain headers.\n* `message.httpVersion`\n* `message.rawHeaders` is modified by the browser, and may not quite match what is sent by\nthe server.\n* `message.trailers` and `message.rawTrailers` will remain empty.\n* Redirects are followed silently by the browser, so it isn't possible to access the 301/302\nredirect pages.\n* The `timeout` event/option and `setTimeout` functions, which operate on the underlying\nsocket, are not available. However, see `options.requestTimeout` above.\n\n## Example\n\n``` js\nhttp.get('/bundle.js', function (res) {\n\tvar div = document.getElementById('result');\n\tdiv.innerHTML += 'GET /beep
';\n\n\tres.on('data', function (buf) {\n\t\tdiv.innerHTML += buf;\n\t});\n\n\tres.on('end', function () {\n\t\tdiv.innerHTML += '
__END__';\n\t});\n})\n```\n\n## Running tests\n\nThere are two sets of tests: the tests that run in Node (found in `test/node`) and the tests\nthat run in the browser (found in `test/browser`). Normally the browser tests run on\n[Sauce Labs](http://saucelabs.com/).\n\nRunning `npm test` will run both sets of tests, but in order for the Sauce Labs tests to run\nyou will need to sign up for an account (free for open source projects) and put the\ncredentials in a [`.airtaprc` file](https://github.com/airtap/airtap/blob/master/doc/airtaprc.md).\nYou will also need to run a [Sauce Connect Proxy](https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy)\nwith the same credentials.\n\nTo run just the Node tests, run `npm run test-node`.\n\nTo run the browser tests locally, run `npm run test-browser-local` and point your browser to\nthe link shown in your terminal.\n\n## License\n\nMIT. Copyright (C) John Hiesey and other contributors.\n", "maintainers": [ { "name": "feross", diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/traverse.json b/workspaces/arborist/test/fixtures/registry-mocks/content/traverse.json index 36830184d2fcd..98cf47e6871a8 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/traverse.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/traverse.json @@ -1480,7 +1480,7 @@ "johnloy": true, "laomu": true }, - "readme": "# traverse\n\nTraverse and transform objects by visiting every node on a recursive walk.\n\n[![browser support](http://ci.testling.com/substack/js-traverse.png)](http://ci.testling.com/substack/js-traverse)\n\n[![build status](https://secure.travis-ci.org/substack/js-traverse.png)](http://travis-ci.org/substack/js-traverse)\n\n# examples\n\n## transform negative numbers in-place\n\nnegative.js\n\n````javascript\nvar traverse = require('traverse');\nvar obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];\n\ntraverse(obj).forEach(function (x) {\n if (x < 0) this.update(x + 128);\n});\n\nconsole.dir(obj);\n````\n\nOutput:\n\n [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ]\n\n## collect leaf nodes\n\nleaves.js\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = {\n a : [1,2,3],\n b : 4,\n c : [5,6],\n d : { e : [7,8], f : 9 },\n};\n\nvar leaves = traverse(obj).reduce(function (acc, x) {\n if (this.isLeaf) acc.push(x);\n return acc;\n}, []);\n\nconsole.dir(leaves);\n````\n\nOutput:\n\n [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n\n## scrub circular references\n\nscrub.js:\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = { a : 1, b : 2, c : [ 3, 4 ] };\nobj.c.push(obj);\n\nvar scrubbed = traverse(obj).map(function (x) {\n if (this.circular) this.remove()\n});\nconsole.dir(scrubbed);\n````\n\noutput:\n\n { a: 1, b: 2, c: [ 3, 4 ] }\n\n# methods\n\nEach method that takes an `fn` uses the context documented below in the context\nsection.\n\n## .map(fn)\n\nExecute `fn` for each node in the object and return a new object with the\nresults of the walk. To update nodes in the result use `this.update(value)`.\n\n## .forEach(fn)\n\nExecute `fn` for each node in the object but unlike `.map()`, when\n`this.update()` is called it updates the object in-place.\n\n## .reduce(fn, acc)\n\nFor each node in the object, perform a\n[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function))\nwith the return value of `fn(acc, node)`.\n\nIf `acc` isn't specified, `acc` is set to the root object for the first step\nand the root element is skipped.\n\n## .paths()\n\nReturn an `Array` of every possible non-cyclic path in the object.\nPaths are `Array`s of string keys.\n\n## .nodes()\n\nReturn an `Array` of every node in the object.\n\n## .clone()\n\nCreate a deep clone of the object.\n\n## .get(path)\n\nGet the element at the array `path`.\n\n## .set(path, value)\n\nSet the element at the array `path` to `value`.\n\n## .has(path)\n\nReturn whether the element at the array `path` exists.\n\n# context\n\nEach method that takes a callback has a context (its `this` object) with these\nattributes:\n\n## this.node\n\nThe present node on the recursive walk\n\n## this.path\n\nAn array of string keys from the root to the present node\n\n## this.parent\n\nThe context of the node's parent.\nThis is `undefined` for the root node.\n\n## this.key\n\nThe name of the key of the present node in its parent.\nThis is `undefined` for the root node.\n\n## this.isRoot, this.notRoot\n\nWhether the present node is the root node\n\n## this.isLeaf, this.notLeaf\n\nWhether or not the present node is a leaf node (has no children)\n\n## this.level\n\nDepth of the node within the traversal\n\n## this.circular\n\nIf the node equals one of its parents, the `circular` attribute is set to the\ncontext of that parent and the traversal progresses no deeper.\n\n## this.update(value, stopHere=false)\n\nSet a new value for the present node.\n\nAll the elements in `value` will be recursively traversed unless `stopHere` is\ntrue.\n\n## this.remove(stopHere=false)\n\nRemove the current element from the output. If the node is in an Array it will\nbe spliced off. Otherwise it will be deleted from its parent.\n\n## this.delete(stopHere=false)\n\nDelete the current element from its parent in the output. Calls `delete` even on\nArrays.\n\n## this.before(fn)\n\nCall this function before any of the children are traversed.\n\nYou can assign into `this.keys` here to traverse in a custom order.\n\n## this.after(fn)\n\nCall this function after any of the children are traversed.\n\n## this.pre(fn)\n\nCall this function before each of the children are traversed.\n\n## this.post(fn)\n\nCall this function after each of the children are traversed.\n\n\n# install\n\nUsing [npm](http://npmjs.org) do:\n\n $ npm install traverse\n\n# license\n\nMIT\n", + "readme": "# traverse\n\nTraverse and transform objects by visiting every node on a recursive walk.\n\n[![browser support](http://ci.testling.com/substack/js-traverse.png)](http://ci.testling.com/substack/js-traverse)\n\n[![build status](https://secure.travis-ci.org/substack/js-traverse.png)](http://travis-ci.org/substack/js-traverse)\n\n# examples\n\n## transform negative numbers in-place\n\nnegative.js\n\n````javascript\nvar traverse = require('traverse');\nvar obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];\n\ntraverse(obj).forEach(function (x) {\n if (x < 0) this.update(x + 128);\n});\n\nconsole.dir(obj);\n````\n\nOutput:\n\n [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ]\n\n## collect leaf nodes\n\nleaves.js\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = {\n a : [1,2,3],\n b : 4,\n c : [5,6],\n d : { e : [7,8], f : 9 },\n};\n\nvar leaves = traverse(obj).reduce(function (acc, x) {\n if (this.isLeaf) acc.push(x);\n return acc;\n}, []);\n\nconsole.dir(leaves);\n````\n\nOutput:\n\n [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n\n## scrub circular references\n\nscrub.js:\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = { a : 1, b : 2, c : [ 3, 4 ] };\nobj.c.push(obj);\n\nvar scrubbed = traverse(obj).map(function (x) {\n if (this.circular) this.remove()\n});\nconsole.dir(scrubbed);\n````\n\noutput:\n\n { a: 1, b: 2, c: [ 3, 4 ] }\n\n# methods\n\nEach method that takes an `fn` uses the context documented below in the context\nsection.\n\n## .map(fn)\n\nExecute `fn` for each node in the object and return a new object with the\nresults of the walk. To update nodes in the result use `this.update(value)`.\n\n## .forEach(fn)\n\nExecute `fn` for each node in the object but unlike `.map()`, when\n`this.update()` is called it updates the object in-place.\n\n## .reduce(fn, acc)\n\nFor each node in the object, perform a\n[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function))\nwith the return value of `fn(acc, node)`.\n\nIf `acc` isn't specified, `acc` is set to the root object for the first step\nand the root element is skipped.\n\n## .paths()\n\nReturn an `Array` of every possible non-cyclic path in the object.\nPaths are `Array`s of string keys.\n\n## .nodes()\n\nReturn an `Array` of every node in the object.\n\n## .clone()\n\nCreate a deep clone of the object.\n\n## .get(path)\n\nGet the element at the array `path`.\n\n## .set(path, value)\n\nSet the element at the array `path` to `value`.\n\n## .has(path)\n\nReturn whether the element at the array `path` exists.\n\n# context\n\nEach method that takes a callback has a context (its `this` object) with these\nattributes:\n\n## this.node\n\nThe present node on the recursive walk\n\n## this.path\n\nAn array of string keys from the root to the present node\n\n## this.parent\n\nThe context of the node's parent.\nThis is `undefined` for the root node.\n\n## this.key\n\nThe name of the key of the present node in its parent.\nThis is `undefined` for the root node.\n\n## this.isRoot, this.notRoot\n\nWhether the present node is the root node\n\n## this.isLeaf, this.notLeaf\n\nWhether or not the present node is a leaf node (has no children)\n\n## this.level\n\nDepth of the node within the traversal\n\n## this.circular\n\nIf the node equals one of its parents, the `circular` attribute is set to the\ncontext of that parent and the traversal progresses no deeper.\n\n## this.update(value, stopHere=false)\n\nSet a new value for the present node.\n\nAll the elements in `value` will be recursively traversed unless `stopHere` is\ntrue.\n\n## this.remove(stopHere=false)\n\nRemove the current element from the output. If the node is in an Array it will\nbe spliced off. Otherwise it will be deleted from its parent.\n\n## this.delete(stopHere=false)\n\nDelete the current element from its parent in the output. Calls `delete` even on\nArrays.\n\n## this.before(fn)\n\nCall this function before any of the children are traversed.\n\nYou can assign into `this.keys` here to traverse in a custom order.\n\n## this.after(fn)\n\nCall this function after any of the children are traversed.\n\n## this.pre(fn)\n\nCall this function beforeEach of the children are traversed.\n\n## this.post(fn)\n\nCall this function afterEach of the children are traversed.\n\n\n# install\n\nUsing [npm](http://npmjs.org) do:\n\n $ npm install traverse\n\n# license\n\nMIT\n", "readmeFilename": "readme.markdown", "homepage": "https://github.com/substack/js-traverse", "keywords": [ diff --git a/workspaces/arborist/test/fixtures/registry-mocks/content/treport.json b/workspaces/arborist/test/fixtures/registry-mocks/content/treport.json index 0fa63cd6ce324..be2d6699ffb35 100644 --- a/workspaces/arborist/test/fixtures/registry-mocks/content/treport.json +++ b/workspaces/arborist/test/fixtures/registry-mocks/content/treport.json @@ -1739,7 +1739,7 @@ "url": "https://izs.me" }, "license": "ISC", - "readme": "# treporter\n\nReporters for node-tap\n\nAn [ink](http://npm.im/ink)-based reporter for use with\n[tap](http://npm.im/tap) version 13 and higher.\n\n## Built-in Report Types\n\n### Base\n\nThe default, and the class to extend to create new reporters. Does all the\nthings, handles all the edge cases, and ends with a pleasant surprise.\n\n### Terse\n\nA lot like Base, but says a lot less. No timer, no list of tests concurrently\nrunning, nothing printed on test passing. Just the failures and the terse\nsummary.\n\n### Specy\n\nA `spec` style reporter with the current running jobs and Terse summary and\nfooter.\n\n## Extending\n\nYou can extend this by creating a module whose main `module.exports` is a\nchild class that extends the `treport.Base` class (which in turn extends\n`React.Component`).\n\n```js\nconst React = require('react')\nconst {Base} = require('treport')\nclass MyTreportBasedTapReporter extends Base {\n // my stuff...\n}\nmodule.exports = MyTreportBasedTapReporter\n```\n\nTo use your module as the test reporter, you'd do this:\n\n```\nnpm install -D my-treport-based-tap-reporter\ntap --reporter=my-treport-based-tap-reporter\n```\n\nTap will `require()` that module, see it's a `React.Component`, and use it\nwith ink.\n\nYour child class will get its `constructor()` called with `{tap:tap}`,\nwhich is the root tap object for the test runner.\n\nIt can override the `render()` method, or anything else. In most cases, you\nwill likely want to override just part of the class, or one of the tags used\nfor the layout, but the sky is the limit. A child class could also modify the\ndata being tracked, but leave the tags untouched.\n\nThe following methods describe each of the class methods that can be\noverridden.\n\n### render()\n\nThe main rendering entry point, as is the React custom. The Base class\nreturns:\n\n```jsx\n\n \n \n { this.state.results ? (\n \n )\n : '' }\n \n\n```\n\nOne of the easiest ways to change the look and feel of the test reporter is to\nswap out these components.\n\n### get Log()\n\nA getter function that returns the React component for the \"log\" section. This\nsection gets failure/todo/skip results pushed into it, as well as the final\npass/fail/todo/skip result for tests when they complete. Typically, it should\nuse a `` tag, since this will often get much longer than the height of\nthe terminal window, and you want to be able to see the results.\n\nSee `state.log` below for more info.\n\n### get Runs()\n\n- `runs` Array of Test objects\n\nA getter function that returns the React component for the \"runs\" section.\n`this.state.runs` is a list of the tests currently in progress.\n\n### get Summary()\n\nThis is a section that shows when the test run is fully completed. It shows a\npretty banner with rainbows, along with any tests that failed, or are marked as\nskip or todo.\n\n### get Footer()\n\nThis is a section that shows the count of test suites (ie, processes) queued\nand completed, a count of assertions completed, and a timer so you can see how\nlong the test is running for.\n\n## State Properties\n\nThe reporter keeps the following state properties up to date as the test\nproceeds:\n\n### this.state.log\n\nArray of log objects. Each is one of the following types:\n\n- `{ raw: }` just a plain old string.\n- `{ res: {ok, name, diag, todo, skip, testName} }` A test point\n- `{ test: [Test Object] }` A test that has completed\n\n### this.state.tests\n\nAll tests are added to this array. In the event of a bailout, everything other\nthan the bailing-out test is removed, so that the Summary output isn't\ncluttered up with a bunch of spurious failures.\n\n### this.state.runs\n\nArray of tests currently running. (When not running in parallel mode, this is\nalways a single item.)\n\n### this.state.results\n\nThe `tap.results` object at the end of the test run.\n\n### this.state.assertCounts\n\nCounts of all assertions run in all tests. `{total, pass, fail, skip, todo}`\n\nIn order to avoid overwhelming the display, updates to assertion counts are\ndebounced so that they are not updated more than once every 50ms.\n\n### this.state.suiteCounts\n\nJust like `assertCounts`, but for test suites, and not debounced.\n\n### this.state.time\n\nTotal elapsed time in ms since the test run started.\n\n### this.state.bailout\n\nWhen a bailout occurs, this is set to the bailout reason, or `true` if no\nreason is given.\n\n### this.start\n\nThe `Date.now()` when the test run started.\n\n### this.assertCounts\n\nUpdated on each test assertion. Matched to `this.state.assertCounts` at most\nonce every 50ms.\n\n### constructor()\n\nThe constructor receives `tap` as an argument, initializes state, and assigns\nappropriate event handlers to keep state up to date. Then, the\n`this.tapResume(tap)` method is called to resume and discard the TAP output\nfrom the test harness, since the reporter gets everything it needs from the\nevents and child test objects.\n\n### tapResume(tap)\n\nOverride to prevent the `tap` object from being resumed when calling the Base\nconstructor.\n\n### get time()\n\nCalled to get the current running time.\n\n### bailout(bailout, test = null)\n\nCalled when a test bails out. If `test` is set to null, then that means that\nthe root Tap test is bailing out independently of any child test. (This is\nunusual.)\n\n### inc(type)\n\nCalled on each assertion to increment `this.assertCounts` and\n`this.state.assertCounts`.\n\n### addTest(test)\n\nCalled whenever a new test is added to the queue (but before it has started\nrunning).\n\n### startTest(test)\n\nCalled when a test starts.\n\n### endTest(test)\n\nCalled when a test ends.\n\n### endAll(tap)\n\nCalled when the main all tests are done and the tap test runner completes.\n\n### logRes(test, res)\n\nCalled when a fail/todo/skip result is emitted from a test, and pushes it onto\nthe log.\n\n### onRaw(test, fd)\n\nReturns a handler to take all the non-TAP data from a child test, so that it\ncan be printed to the log with a helpful prefix. In the Base test class, this\nprefixes with the name of the test and the file descriptor printed to.\n\nSo, for example, a test named `test/foo.js` would have its stderr output\nprefixed with `test/foo.js 2> ...` and its stdout output prefixed with\n`test/foo.js 1> ...`.\n", + "readme": "# treporter\n\nReporters for node-tap\n\nAn [ink](http://npm.im/ink)-based reporter for use with\n[tap](http://npm.im/tap) version 13 and higher.\n\n## Built-in Report Types\n\n### Base\n\nThe default, and the class to extend to create new reporters. Does all the\nthings, handles all the edge cases, and ends with a pleasant surprise.\n\n### Terse\n\nA lot like Base, but says a lot less. No timer, no list of tests concurrently\nrunning, nothing printed on test passing. Just the failures and the terse\nsummary.\n\n### Specy\n\nA `spec` style reporter with the current running jobs and Terse summary and\nfooter.\n\n## Extending\n\nYou can extend this by creating a module whose main `module.exports` is a\nchild class that extends the `treport.Base` class (which in turn extends\n`React.Component`).\n\n```js\nconst React = require('react')\nconst {Base} = require('treport')\nclass MyTreportBasedTapReporter extends Base {\n // my stuff...\n}\nmodule.exports = MyTreportBasedTapReporter\n```\n\nTo use your module as the test reporter, you'd do this:\n\n```\nnpm install -D my-treport-based-tap-reporter\ntap --reporter=my-treport-based-tap-reporter\n```\n\nTap will `require()` that module, see it's a `React.Component`, and use it\nwith ink.\n\nYour child class will get its `constructor()` called with `{tap:tap}`,\nwhich is the root tap object for the test runner.\n\nIt can override the `render()` method, or anything else. In most cases, you\nwill likely want to override just part of the class, or one of the tags used\nfor the layout, but the sky is the limit. A child class could also modify the\ndata being tracked, but leave the tags untouched.\n\nThe following methods describe.each of the class methods that can be\noverridden.\n\n### render()\n\nThe main rendering entry point, as is the React custom. The Base class\nreturns:\n\n```jsx\n\n \n \n { this.state.results ? (\n \n )\n : '' }\n \n\n```\n\nOne of the easiest ways to change the look and feel of the test reporter is to\nswap out these components.\n\n### get Log()\n\nA getter function that returns the React component for the \"log\" section. This\nsection gets failure/todo/skip results pushed into it, as well as the final\npass/fail/todo/skip result for tests when they complete. Typically, it should\nuse a `` tag, since this will often get much longer than the height of\nthe terminal window, and you want to be able to see the results.\n\nSee `state.log` below for more info.\n\n### get Runs()\n\n- `runs` Array of Test objects\n\nA getter function that returns the React component for the \"runs\" section.\n`this.state.runs` is a list of the tests currently in progress.\n\n### get Summary()\n\nThis is a section that shows when the test run is fully completed. It shows a\npretty banner with rainbows, along with any tests that failed, or are marked as\nskip or todo.\n\n### get Footer()\n\nThis is a section that shows the count of test suites (ie, processes) queued\nand completed, a count of assertions completed, and a timer so you can see how\nlong the test is running for.\n\n## State Properties\n\nThe reporter keeps the following state properties up to date as the test\nproceeds:\n\n### this.state.log\n\nArray of log objects. Each is one of the following types:\n\n- `{ raw: }` just a plain old string.\n- `{ res: {ok, name, diag, todo, skip, testName} }` A test point\n- `{ test: [Test Object] }` A test that has completed\n\n### this.state.tests\n\nAll tests are added to this array. In the event of a bailout, everything other\nthan the bailing-out test is removed, so that the Summary output isn't\ncluttered up with a bunch of spurious failures.\n\n### this.state.runs\n\nArray of tests currently running. (When not running in parallel mode, this is\nalways a single item.)\n\n### this.state.results\n\nThe `tap.results` object at the end of the test run.\n\n### this.state.assertCounts\n\nCounts of all assertions run in all tests. `{total, pass, fail, skip, todo}`\n\nIn order to avoid overwhelming the display, updates to assertion counts are\ndebounced so that they are not updated more than once every 50ms.\n\n### this.state.suiteCounts\n\nJust like `assertCounts`, but for test suites, and not debounced.\n\n### this.state.time\n\nTotal elapsed time in ms since the test run started.\n\n### this.state.bailout\n\nWhen a bailout occurs, this is set to the bailout reason, or `true` if no\nreason is given.\n\n### this.start\n\nThe `Date.now()` when the test run started.\n\n### this.assertCounts\n\nUpdated on each test assertion. Matched to `this.state.assertCounts` at most\nonce every 50ms.\n\n### constructor()\n\nThe constructor receives `tap` as an argument, initializes state, and assigns\nappropriate event handlers to keep state up to date. Then, the\n`this.tapResume(tap)` method is called to resume and discard the TAP output\nfrom the test harness, since the reporter gets everything it needs from the\nevents and child test objects.\n\n### tapResume(tap)\n\nOverride to prevent the `tap` object from being resumed when calling the Base\nconstructor.\n\n### get time()\n\nCalled to get the current running time.\n\n### bailout(bailout, test = null)\n\nCalled when a test bails out. If `test` is set to null, then that means that\nthe root Tap test is bailing out independently of any child test. (This is\nunusual.)\n\n### inc(type)\n\nCalled on each assertion to increment `this.assertCounts` and\n`this.state.assertCounts`.\n\n### addTest(test)\n\nCalled whenever a new test is added to the queue (but before it has started\nrunning).\n\n### startTest(test)\n\nCalled when a test starts.\n\n### endTest(test)\n\nCalled when a test ends.\n\n### endAll(tap)\n\nCalled when the main all tests are done and the tap test runner completes.\n\n### logRes(test, res)\n\nCalled when a fail/todo/skip result is emitted from a test, and pushes it onto\nthe log.\n\n### onRaw(test, fd)\n\nReturns a handler to take all the non-TAP data from a child test, so that it\ncan be printed to the log with a helpful prefix. In the Base test class, this\nprefixes with the name of the test and the file descriptor printed to.\n\nSo, for example, a test named `test/foo.js` would have its stderr output\nprefixed with `test/foo.js 2> ...` and its stdout output prefixed with\n`test/foo.js 1> ...`.\n", "readmeFilename": "README.md", "homepage": "https://github.com/tapjs/treport#readme", "repository": { diff --git a/workspaces/libnpmdiff/README.md b/workspaces/libnpmdiff/README.md index 0b329df0a2bad..620054caaa5ab 100644 --- a/workspaces/libnpmdiff/README.md +++ b/workspaces/libnpmdiff/README.md @@ -75,7 +75,7 @@ Fetches the registry tarballs and compare files between a spec `a` and spec `b`. Defaults to `false`. - `tagVersionPrefix `: What prefix should be used to define version numbers. Defaults to `v` -- `diffUnified `: How many lines of code to print before/after each diff. +- `diffUnified `: How many lines of code to print before/afterEach diff. Defaults to `3`. - `diffFiles >`: If set only prints patches for the files listed in this array (also accepts globs). Defaults to `undefined`. diff --git a/workspaces/libnpmexec/test/local.js b/workspaces/libnpmexec/test/local.js index 5b0133105393d..52a7e6e60cba6 100644 --- a/workspaces/libnpmexec/test/local.js +++ b/workspaces/libnpmexec/test/local.js @@ -57,7 +57,7 @@ t.test('bin in local pkg', async t => { await chmod('bin-dir/nested-bin-test.js') await chmod('node_modules/pkg-with-conflicting-bin/index.js') - // Note that we have to resetSeenLinks after each exec since otherwise + // Note that we have to resetSeenLinks afterEach exec since otherwise // our nonexistent file will fail when it gets attempted to get chmod'ed // in a real world situation these would happen during different // processes where these is no shared cache