{"_id":"@foxglove/node-fetch","_rev":"7-e9d4ced3842d1fd00f913164fc31a40f","name":"@foxglove/node-fetch","dist-tags":{"latest":"3.1.0"},"versions":{"3.1.0":{"name":"@foxglove/node-fetch","version":"3.1.0","description":"A light-weight module that brings Fetch API to node.js","main":"./dist/index.cjs","module":"./src/index.js","sideEffects":false,"type":"module","exports":{".":{"import":"./src/index.js","require":"./dist/index.cjs"},"./package.json":"./package.json"},"types":"./@types/index.d.ts","engines":{"node":"^10.17 || >=12.3"},"scripts":{"build":"rollup -c","test":"node --experimental-modules node_modules/c8/bin/c8 --reporter=html --reporter=lcov --reporter=text --check-coverage node --experimental-modules node_modules/mocha/bin/mocha","coverage":"c8 report --reporter=text-lcov | coveralls","test-types":"tsd","lint":"xo","prepublishOnly":"node ./test/commonjs/test-artifact.js"},"repository":{"type":"git","url":"git+https://github.com/node-fetch/node-fetch.git"},"keywords":["fetch","http","promise","request","curl","wget","xhr","whatwg"],"author":{"name":"David Frank"},"license":"MIT","bugs":{"url":"https://github.com/node-fetch/node-fetch/issues"},"homepage":"https://github.com/node-fetch/node-fetch","funding":{"type":"opencollective","url":"https://opencollective.com/node-fetch"},"devDependencies":{"abort-controller":"^3.0.0","abortcontroller-polyfill":"^1.7.1","busboy":"^0.3.1","c8":"^7.3.0","chai":"^4.2.0","chai-as-promised":"^7.1.1","chai-iterator":"^3.0.2","chai-string":"^1.5.0","coveralls":"^3.1.0","delay":"^4.4.0","form-data":"^3.0.0","formdata-node":"^2.4.0","mocha":"^8.1.3","p-timeout":"^3.2.0","rollup":"^2.26.10","tsd":"^0.13.1","xo":"^0.33.1"},"dependencies":{"data-uri-to-buffer":"^3.0.1","fetch-blob":"^2.1.1"},"esm":{"sourceMap":true,"cjs":false},"tsd":{"cwd":"@types","compilerOptions":{"target":"esnext","lib":["es2018"],"allowSyntheticDefaultImports":false,"esModuleInterop":false}},"xo":{"envs":["node","browser"],"rules":{"complexity":0,"import/extensions":0,"import/no-useless-path-segments":0,"import/no-anonymous-default-export":0,"unicorn/import-index":0,"unicorn/no-reduce":0,"capitalized-comments":0},"ignores":["dist","@types"],"overrides":[{"files":"test/**/*.js","envs":["node","mocha"],"rules":{"max-nested-callbacks":0,"no-unused-expressions":0,"new-cap":0,"guard-for-in":0,"unicorn/prevent-abbreviations":0,"promise/prefer-await-to-then":0,"ava/no-import-test-files":0}},{"files":"example.js","rules":{"import/no-extraneous-dependencies":0}}]},"runkitExampleFilename":"example.js","gitHead":"ffef5e3c2322e8493dd75120b1123b01b106ab23","_id":"@foxglove/node-fetch@3.1.0","_nodeVersion":"16.4.0","_npmVersion":"7.18.1","dist":{"integrity":"sha512-pfFDGz0lTI67MuX80LA0b6O/yv6if0rBYH5Bub/LCUAFvcvS7ubpluwsWCOhV0TyiC1wvbCX8/0j9BR1kBLiew==","shasum":"4e721a5552626fdbec885fee23035e834926d916","tarball":"https://registry.npmjs.org/@foxglove/node-fetch/-/node-fetch-3.1.0.tgz","fileCount":18,"unpackedSize":197625,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJg731yCRA9TVsSAnZWagAAHr4P/AvV45p8VLoRw80uI+hv\nPDYFuQzRTnRLyWKGWfwzi7WVHpcPYYzutfktzWKR1x7iQvWaYpRtteTUJDDI\ncolvbZ1uaOHqoF7SrKraVgCojz7D3yLEUdHN3sf2KFWXAeMvEQzE5qL2hz8z\n/HymIFDORv5mvxvCq4CAq0t8I/s2EGqxtP8hOTYWL0k89C40P1/bBuxLviiW\nQGTeeEZXEZUsR34f25DcCb24vaXc+QulLVBETmVll03uvP1+3+7dWTbckQXe\nRd2378S0ImYQhkpnAvETxl6c1YDmeJK00sUmqVLRTa7aZBx82W/ddRoPSJks\nTSy1WCw7oP8mt3KGuU8dSDpREzw/uBdwwLsQI3MZXaJQpBBT45tCgd8Xv7qz\n8XdydqZvjVJd1eNql61YXo05PKhodFbu4Bk1z+dC5YQLpqFDBWMW03zY9c4O\n7A+2sfBBO2k2HRTqiWy/0IotUkC63R/ch6/aXH7du/9fTPBfwy0+efA/ixco\n2qtrqkvqf6QyaUG1o1Xof0JH6wo50KfugNTtLBfBp34AARC5vnUTXQK2mpj2\nT1oF8hRl4OKVIeqZ8yGTtif670G/ImxQR0vEKJrGgVotFMR3LG4O5rL5+Hfo\nTRjgPL5M29plBp1SYFHuSL8pbFFDqVwSuKIz5xVJrYUFvxPXyrl4XCBluvMA\n5K8l\r\n=m2s2\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCr7Z3+7tQPYgfpGxhyU4LgmIZG85LQ2s5wvFsu0oc8oAIgfF9HlbwmU7z8M8P4+IzwknsOcix2ImZx8hF7NeCDafw="}]},"_npmUser":{"name":"jhurliman","email":"jhurliman@jhurliman.org"},"directories":{},"maintainers":[{"name":"foxglove-npmpublishbot","email":"adrian+foxglove-npmpublishbot@foxglove.dev"},{"name":"defunctzombie","email":"shtylman@gmail.com"},{"name":"jhurliman","email":"jhurliman@jhurliman.org"},{"name":"amacneil","email":"adrian.macneil@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/node-fetch_3.1.0_1626307953779_0.4913747203027645"},"_hasShrinkwrap":false}},"time":{"created":"2021-07-15T00:12:33.427Z","3.1.0":"2021-07-15T00:12:33.927Z","modified":"2022-04-05T12:09:38.929Z"},"maintainers":[{"email":"adrian+foxglovebot@foxglove.dev","name":"foxglovebot"},{"email":"adrian.macneil@gmail.com","name":"amacneil"}],"description":"A light-weight module that brings Fetch API to node.js","homepage":"https://github.com/node-fetch/node-fetch","keywords":["fetch","http","promise","request","curl","wget","xhr","whatwg"],"repository":{"type":"git","url":"git+https://github.com/node-fetch/node-fetch.git"},"author":{"name":"David Frank"},"bugs":{"url":"https://github.com/node-fetch/node-fetch/issues"},"license":"MIT","readme":"<div align=\"center\">\n\t<img src=\"docs/media/Banner.svg\" alt=\"Node Fetch\"/>\n\t<br>\n\t<p>A light-weight module that brings <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\">Fetch API</a> to Node.js.</p>\n\t<a href=\"https://github.com/node-fetch/node-fetch/actions\"><img src=\"https://github.com/node-fetch/node-fetch/workflows/CI/badge.svg?branch=master\" alt=\"Build status\"></a>\n\t<a href=\"https://coveralls.io/github/node-fetch/node-fetch\"><img src=\"https://img.shields.io/coveralls/github/node-fetch/node-fetch\" alt=\"Coverage status\"></a>\n\t<a href=\"https://packagephobia.now.sh/result?p=node-fetch\"><img src=\"https://badgen.net/packagephobia/install/node-fetch\" alt=\"Current version\"></a>\n\t<a href=\"https://www.npmjs.com/package/node-fetch\"><img src=\"https://img.shields.io/npm/v/node-fetch\" alt=\"Install size\"></a>\n\t<a href=\"https://github.com/sindresorhus/awesome-nodejs\"><img src=\"https://awesome.re/mentioned-badge.svg\" alt=\"Mentioned in Awesome Node.js\"></a>\n\t<a href=\"https://discord.gg/Zxbndcm\"><img src=\"https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord\" alt=\"Discord\"></a>\n\t<br>\n\t<br>\n\t<b>Consider supporting us on our Open Collective:</b>\n\t<br>\n\t<br>\n\t<a href=\"https://opencollective.com/node-fetch\"><img src=\"https://opencollective.com/node-fetch/donate/button.png?color=blue\" alt=\"Open Collective\"></a>\n</div>\n\n---\n\n<!-- TOC -->\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\t- [response.type](#responsetype)\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<!-- /TOC -->\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\nnpm 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\tglobalThis.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\nconst response = await fetch('https://github.com/');\nconst body = await response.text();\n\nconsole.log(body);\n```\n\n### JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst response = await fetch('https://api.github.com/users/github');\nconst data = await response.json();\n\nconsole.log(data);\n```\n\n### Simple Post\n\n```js\nconst fetch = require('node-fetch');\n\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\nconst data = await response.json();\n\nconsole.log(data);\n```\n\n### Post with JSON\n\n```js\nconst fetch = require('node-fetch');\n\nconst body = {a: 1};\n\nconst response = await fetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n});\nconst data = await response.json();\n\nconsole.log(data);\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\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\nconst data = await response.json();\n\nconsole.log(data);\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\tawait fetch('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\nclass HTTPResponseError extends Error {\n\tconstructor(response, ...args) {\n\t\tthis.response = response;\n\t\tsuper(`HTTP Error Response: ${response.status} ${response.statusText}`, ...args);\n\t}\n}\n\nconst checkStatus = response => {\n\tif (response.ok) {\n\t\t// response.status >= 200 && response.status < 300\n\t\treturn response;\n\t} else {\n\t\tthrow new HTTPResponseError(response);\n\t}\n}\n\nconst response = await fetch('https://httpbin.org/status/400');\n\ntry {\n\tcheckStatus(response);\n} catch (error) {\n\tconsole.error(error);\n\n\tconst errorBody = await error.response.text();\n\tconsole.error(`Error body: ${errorBody}`);\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 {createWriteStream} = require('fs');\nconst {pipeline} = require('stream');\nconst {promisify} = require('util');\nconst fetch = require('node-fetch');\n\nconst streamPipeline = promisify(pipeline);\n\nconst response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');\n\nif (!response.ok) throw new Error(`unexpected response ${response.statusText}`);\n\nawait streamPipeline(response.body, createWriteStream('./octocat.png'));\n```\n\nIn Node.js 14 you can also use async iterators to read `body`; however, be careful to catch\nerrors -- the longer a response runs, the more likely it is to encounter an error.\n\n```js\nconst fetch = require('node-fetch');\n\nconst response = await fetch('https://httpbin.org/stream/3');\n\ntry {\n\tfor await (const chunk of response.body) {\n\t\tconsole.dir(JSON.parse(chunk.toString()));\n\t}\n} catch (err) {\n\tconsole.error(err.stack);\n}\n```\n\nIn Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams\ndid not mature until Node.js 14, so you need to do some extra work to ensure you handle errors\ndirectly from the stream and wait on it response to fully close.\n\n```js\nconst fetch = require('node-fetch');\n\nconst read = async body => {\n\tlet error;\n\tbody.on('error', err => {\n\t\terror = err;\n\t});\n\n\tfor await (const chunk of body) {\n\t\tconsole.dir(JSON.parse(chunk.toString()));\n\t}\n\n\treturn new Promise((resolve, reject) => {\n\t\tbody.on('close', () => {\n\t\t\terror ? reject(error) : resolve();\n\t\t});\n\t});\n};\n\ntry {\n\tconst response = await fetch('https://httpbin.org/stream/3');\n\tawait read(response.body);\n} catch (err) {\n\tconsole.error(err.stack);\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\nconst response = await fetch('https://octodex.github.com/images/Fintechtocat.png');\nconst buffer = await response.buffer();\nconst type = await fileType.fromBuffer(buffer)\n\nconsole.log(type);\n```\n\n### Accessing Headers and other Meta data\n\n```js\nconst fetch = require('node-fetch');\n\nconst response = await fetch('https://github.com/');\n\nconsole.log(response.ok);\nconsole.log(response.status);\nconsole.log(response.statusText);\nconsole.log(response.headers.raw());\nconsole.log(response.headers.get('content-type'));\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\nconst response = await fetch('https://example.com');\n\n// Returns an array of values, instead of a string of comma-separated values\nconsole.log(response.headers.raw()['set-cookie']);\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\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});\nconst data = await response.json();\n\nconsole.log(data)\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\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\nconst data = await response.json();\n\nconsole.log(data)\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\nconst response = await fetch('https://httpbin.org/post', options);\nconst data = await response.json();\n\nconsole.log(data)\n```\n\nnode-fetch also supports spec-compliant FormData implementations such as [form-data](https://github.com/form-data/form-data) and [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\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});\nconst data = await response.json();\n\nconsole.log(data);\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\ntry {\n\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\tconst data = await response.json();\n} catch (error) {\n\tif (error instanceof fetch.AbortError) {\n\t\tconsole.log('request was aborted');\n\t}\n} finally {\n\tclearTimeout(timeout);\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: <code>Promise&lt;[Response](#class-response)&gt;</code>\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<a id=\"fetch-options\"></a>\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n\t// These properties are part of the Fetch Standard\n\tmethod: 'GET',\n\theaders: {},            // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n\tbody: null,             // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n\tredirect: 'follow',     // Set to `manual` to extract redirect headers, `error` to reject redirect\n\tsignal: null,           // Pass an instance of AbortSignal to optionally abort requests\n\n\t// The following properties are node-fetch extensions\n\tfollow: 20,             // maximum redirect count. 0 to not follow redirect\n\tcompress: true,         // support gzip/deflate content encoding. false to disable\n\tsize: 0,                // maximum response body size in bytes. 0 to disable\n\tagent: null,            // http(s).Agent instance or function that returns an instance (see below)\n\thighWaterMark: 16384,   // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n\tinsecureHTTPParser: 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<a id=\"custom-highWaterMark\"></a>\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\nconst response = await fetch('https://example.com');\nconst r1 = await response.clone();\n\nconst results = await Promise.all([response.json(), r1.text()]);\n\nconsole.log(results[0]);\nconsole.log(results[1]);\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\nconst response = await fetch('https://example.com', {\n\t// About 1MB\n\thighWaterMark: 1024 * 1024\n});\n\nconst result = await res.clone().buffer();\nconsole.dir(result);\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<a id=\"class-request\"></a>\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<small>_(spec-compliant)_</small>\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<a id=\"class-response\"></a>\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- `trailer`\n\n#### new Response([body[, options]])\n\n<small>_(spec-compliant)_</small>\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<small>_(spec-compliant)_</small>\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<small>_(spec-compliant)_</small>\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#### response.type\n\n<small>_(deviation from spec)_</small>\n\nConvenience property representing the response's type. node-fetch only supports `'default'` and `'error'` and does not make use of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response).\n\n<a id=\"class-headers\"></a>\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<small>_(spec-compliant)_</small>\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<a id=\"iface-body\"></a>\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<small>_(deviation from spec)_</small>\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<small>_(spec-compliant)_</small>\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<small>_(spec-compliant)_</small>\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<small>_(node-fetch extension)_</small>\n\n- Returns: `Promise<Buffer>`\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n<a id=\"class-fetcherror\"></a>\n\n### Class: FetchError\n\n<small>_(node-fetch extension)_</small>\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n<a id=\"class-aborterror\"></a>\n\n### Class: AbortError\n\n<small>_(node-fetch extension)_</small>\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\nnpm 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"}