Gathering detailed insights and metrics for node-fetch-h2
Gathering detailed insights and metrics for node-fetch-h2
Gathering detailed insights and metrics for node-fetch-h2
Gathering detailed insights and metrics for node-fetch-h2
A light-weight module that brings window.fetch to Node.js
npm install node-fetch-h2
59.4
Supply Chain
99.6
Quality
75.1
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1 Stars
386 Commits
2 Watching
6 Branches
1 Contributors
Updated on 25 Apr 2023
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-23.4%
226,412
Compared to previous day
Last week
-6.5%
1,423,448
Compared to previous week
Last month
-0.4%
6,317,498
Compared to previous month
Last year
61.3%
65,090,583
Compared to previous year
1
24
A light-weight module that brings window.fetch
to Node.js
(We are looking for v2 maintainers and collaborators)
Instead of implementing XMLHttpRequest
in Node.js to run browser-specific Fetch polyfill, 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.
See Matt Andrews' isomorphic-fetch or Leonardo Quixada's cross-fetch for isomorphic usage (exports node-fetch
for server-side, whatwg-fetch
for client-side).
window.fetch
API.res.text()
and res.json()
) to UTF-8 automatically.window.fetch
offers, feel free to open an issue.Current stable release (2.x
)
1$ npm install node-fetch --save
We suggest you load the module via require
, pending the stabalizing of es modules in node:
1const fetch = require('node-fetch');
If you are using a Promise library other than native, set it through fetch.Promise:
1const Bluebird = require('bluebird'); 2 3fetch.Promise = Bluebird;
NOTE: The documentation below is up-to-date with 2.x
releases, see 1.x
readme, changelog and 2.x upgrade guide for the differences.
1fetch('https://github.com/') 2 .then(res => res.text()) 3 .then(body => console.log(body));
1 2fetch('https://api.github.com/users/github') 3 .then(res => res.json()) 4 .then(json => console.log(json));
1fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) 2 .then(res => res.json()) // expecting a json response 3 .then(json => console.log(json));
1const body = { a: 1 }; 2 3fetch('https://httpbin.org/post', { 4 method: 'post', 5 body: JSON.stringify(body), 6 headers: { 'Content-Type': 'application/json' }, 7 }) 8 .then(res => res.json()) 9 .then(json => console.log(json));
URLSearchParams
is available in Node.js as of v7.5.0. See official documentation for more usage methods.
NOTE: The Content-Type
header is only set automatically to x-www-form-urlencoded
when an instance of URLSearchParams
is given as such:
1const { URLSearchParams } = require('url'); 2 3const params = new URLSearchParams(); 4params.append('a', 1); 5 6fetch('https://httpbin.org/post', { method: 'POST', body: params }) 7 .then(res => res.json()) 8 .then(json => console.log(json));
NOTE: 3xx-5xx responses are NOT exceptions, and should be handled in then()
, see the next section.
Adding 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 for more details.
1fetch('https://domain.invalid/') 2 .catch(err => console.error(err));
It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
1function checkStatus(res) { 2 if (res.ok) { // res.status >= 200 && res.status < 300 3 return res; 4 } else { 5 throw MyCustomError(res.statusText); 6 } 7} 8 9fetch('https://httpbin.org/status/400') 10 .then(checkStatus) 11 .then(res => console.log('will not get here...'))
The "Node.js way" is to use streams when possible:
1fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') 2 .then(res => { 3 const dest = fs.createWriteStream('./octocat.png'); 4 res.body.pipe(dest); 5 });
If you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a node-fetch
only API)
1const fileType = require('file-type'); 2 3fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') 4 .then(res => res.buffer()) 5 .then(buffer => fileType(buffer)) 6 .then(type => { /* ... */ });
1fetch('https://github.com/') 2 .then(res => { 3 console.log(res.ok); 4 console.log(res.status); 5 console.log(res.statusText); 6 console.log(res.headers.raw()); 7 console.log(res.headers.get('content-type')); 8 });
1const { createReadStream } = require('fs'); 2 3const stream = createReadStream('input.txt'); 4 5fetch('https://httpbin.org/post', { method: 'POST', body: stream }) 6 .then(res => res.json()) 7 .then(json => console.log(json));
1const FormData = require('form-data'); 2 3const form = new FormData(); 4form.append('a', 1); 5 6fetch('https://httpbin.org/post', { method: 'POST', body: form }) 7 .then(res => res.json()) 8 .then(json => console.log(json)); 9 10// OR, using custom headers 11// NOTE: getHeaders() is non-standard API 12 13const form = new FormData(); 14form.append('a', 1); 15 16const options = { 17 method: 'POST', 18 body: form, 19 headers: form.getHeaders() 20} 21 22fetch('https://httpbin.org/post', options) 23 .then(res => res.json()) 24 .then(json => console.log(json));
NOTE: You may only cancel streamed requests on Node >= v8.0.0
You may cancel requests with AbortController
. A suggested implementation is abort-controller
.
An example of timing out a request after 150ms could be achieved as follows:
1import AbortController from 'abort-controller'; 2 3const controller = new AbortController(); 4const timeout = setTimeout( 5 () => { controller.abort(); }, 6 150, 7); 8 9fetch(url, { signal: controller.signal }) 10 .then(res => res.json()) 11 .then( 12 data => { 13 useData(data) 14 }, 15 err => { 16 if (err.name === 'AbortError') { 17 // request was aborted 18 } 19 }, 20 ) 21 .finally(() => { 22 clearTimeout(timeout); 23 });
See test cases for more examples.
url
A string representing the URL for fetchingoptions
Options for the HTTP(S) requestPromise<Response>
Perform an HTTP(S) fetch.
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.
The default values are shown after each option key.
1{ 2 // These properties are part of the Fetch Standard 3 method: 'GET', 4 headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) 5 body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream 6 redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect 7 signal: null, // pass an instance of AbortSignal to optionally abort requests 8 9 // The following properties are node-fetch extensions 10 follow: 20, // maximum redirect count. 0 to not follow redirect 11 timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. 12 compress: true, // support gzip/deflate content encoding. false to disable 13 size: 0, // maximum response body size in bytes. 0 to disable 14 agent: null // http(s).Agent instance, allows custom proxy, certificate, dns lookup etc. 15}
If no values are set, the following request headers will be sent automatically:
Header | Value |
---|---|
Accept-Encoding | gzip,deflate (when options.compress === true ) |
Accept | */* |
Connection | close (when no options.agent is present) |
Content-Length | (automatically calculated, if possible) |
Transfer-Encoding | chunked (when req.body is a stream) |
User-Agent | node-fetch/1.0 (+https://github.com/bitinn/node-fetch) |
An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the Body interface.
Due to the nature of Node.js, the following properties are not implemented at this moment:
type
destination
referrer
referrerPolicy
mode
credentials
cache
integrity
keepalive
The following node-fetch extension properties are provided:
follow
compress
counter
agent
See options for exact meaning of these extensions.
(spec-compliant)
input
A string representing a URL, or another Request
(which will be cloned)options
[Options][#fetch-options] for the HTTP(S) requestConstructs a new Request
object. The constructor is identical to that in the browser.
In most cases, directly fetch(url, options)
is simpler than creating a Request
object.
An HTTP(S) response. This class implements the Body interface.
The following properties are not implemented in node-fetch at this moment:
Response.error()
Response.redirect()
type
redirected
trailer
(spec-compliant)
body
A string or Readable streamoptions
A ResponseInit
options dictionaryConstructs a new Response
object. The constructor is identical to that in the browser.
Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a Response
directly.
(spec-compliant)
Convenience 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.
This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the Fetch Standard are implemented.
(spec-compliant)
init
Optional argument to pre-fill the Headers
objectConstruct a new Headers
object. init
can be either null
, a Headers
object, an key-value map object, or any iterable object.
1// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class 2 3const meta = { 4 'Content-Type': 'text/xml', 5 'Breaking-Bad': '<3' 6}; 7const headers = new Headers(meta); 8 9// The above is equivalent to 10const meta = [ 11 [ 'Content-Type', 'text/xml' ], 12 [ 'Breaking-Bad', '<3' ] 13]; 14const headers = new Headers(meta); 15 16// You can in fact use any iterable objects, like a Map or even another Headers 17const meta = new Map(); 18meta.set('Content-Type', 'text/xml'); 19meta.set('Breaking-Bad', '<3'); 20const headers = new Headers(meta); 21const copyOfHeaders = new Headers(headers);
Body
is an abstract interface with methods that are applicable to both Request
and Response
classes.
The following methods are not yet implemented in node-fetch at this moment:
formData()
(deviation from spec)
Readable
streamThe data encapsulated in the Body
object. Note that while the Fetch Standard requires the property to always be a WHATWG ReadableStream
, in node-fetch it is a Node.js Readable
stream.
(spec-compliant)
Boolean
A boolean property for if this body has been consumed. Per spec, a consumed body cannot be used again.
(spec-compliant)
Promise
Consume the body and return a promise that will resolve to one of these formats.
(node-fetch extension)
Promise<Buffer>
Consume the body and return a promise that will resolve to a Buffer.
(node-fetch extension)
Promise<String>
Identical to body.text()
, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8, if possible.
(This API requires an optional dependency on npm package encoding, which you need to install manually. webpack
users may see a warning message due to this optional dependency.)
(node-fetch extension)
An operational error in the fetching process. See ERROR-HANDLING.md for more info.
(node-fetch extension)
An 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.
Thanks to github/fetch for providing a solid implementation reference.
node-fetch
v1 was maintained by @bitinn, v2 is currently maintained by @TimothyGu, v2 readme is written by @jkantr.
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
3 existing vulnerabilities detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More