fetch-as
Fetch data in Node.js
!Follow mefollow-me-badgefollow-me-url
!Versionversion-badgeversion-url !Node versionnode-version-badgenode-version-url !MIT Licensemit-license-badgemit-license-url
!Downloadsdownloads-badgedownloads-url !Total downloadstotal-downloads-badgedownloads-url !Packagephobiapackagephobia-badgepackagephobia-url !Bundlephobiabundlephobia-badgebundlephobia-url
!CircleCIcircleci-badgecircleci-url !Dependency Statusdaviddm-badgedaviddm-url !codecovcodecov-badgecodecov-url !Coverage Statuscoveralls-badgecoveralls-url
!codebeat badgecodebeat-badgecodebeat-url !Codacy Badgecodacy-badgecodacy-url !Code of Conductcoc-badgecoc-url
Fetch API in Node.js with specific response type
Table of contents
- TypeScript or ES modules - Node.js - FetchAsInfo - FetchAsReturnType - fetchAs - fetchAsArrayBuffer(url, options) - fetchAsBlob(url, options) - fetchAsBuffer(url, options) - fetchAsJson(url, options) - fetchAsText(url, options) - fetchAsTextConverted(url, options)Pre-requisites
- Node.jsnode-js-url >= 8.9.0
- NPMnpm-url >= 5.5.1 (NPMnpm-url comes with Node.jsnode-js-url so there is no need to install separately.)
Install
# Install via NPM
$ npm install --save fetch-as
Usage
TypeScript or ES modules
/**
* NOTE: Additional typings file from `node-fetch` is required
* if user decides to create their own `options` and it is based on
* `RequestInit` from `@types/node-fetch`.
*
* Run the following command to install the additional typings:-
*
* $ npm install --dev @types/node-fetch
*/
import { RequestInit } from 'node-fetch';
import fetchAs from 'fetch-as';
// OR import each method explicitly
// import {
// fetchAsArrayBuffer,
// fetchAsBlob,
// fetchAsBuffer,
// fetchAsJson,
// fetchAsText,
// fetchAsTextConverted,
// } from 'fetch-as';
async function runFetch() {
const opts: RequestInit = {
method: 'GET',
};
const url = 'http://www.mocky.io/v2/5a50cfa82f000085158d5315';
const jsonData = await fetchAs.json(url, opts); // OR fetchAsJson(url);
console.log('# json', jsonData.data);
// {
// "status": 200,
// "message": "OK",
// "by": "fetch-as"
// }
}
runFetch();
Node.js
const { fetchAs } = require('fetch-as');
// OR require each method explicitly
// const {
// fetchAsArrayBuffer,
// fetchAsBlob,
// fetchAsBuffer,
// fetchAsJson,
// fetchAsText,
// fetchAsTextConverted,
// } = require('fetch-as');
async function runFetch() {
const url = 'http://www.mocky.io/v2/5a50cfa82f000085158d5315';
const jsonData = await fetchAs.json(url); // OR fetchAsJson(url);
console.log('# json', jsonData.data);
// {
// "status": 200,
// "message": "OK",
// "by": "fetch-as"
// }
}
runFetch();
@types/node-fetch
for TypeScript users
For TypeScripttypescript-url users, you are recommended to install the required typing file from @types/node-fetchtypesnode-fetch-url as one of the devDependencies
for the package to work properly as some of the typings used in the package are from the said typing file but they are not included as part of the bundle.Otherwise, see Optionsnode-fetch-options-url for a list of supported options.
$ npm install --dev @types/node-fetch
API Reference
FetchAsInfo
// Interface
interface FetchAsInfo {
size: number;
timeout: number;
type: "basic"|"cors"|"default"|"error"|"opaque"|"opaqueredirect";
headers: {
[key: string]: any;
};
}
FetchAsReturnType
// Interface
interface FetchAsReturnType<T = any, U = any> {
status: number;
info: FetchAsInfo;
data?: T;
error?: U;
}
status
<stringstring-mdn-url> HTTP response status code. Any response that has a HTTP status greater than399
can be regarded as an error response.info
<Objectobject-mdn-url> This contains additional information you might need from a response. See FetchAsInfofetchasinfo-url for the detailed interface.
size
<numbernumber-mdn-url> Response size.
- timeout
<numbernumber-mdn-url> Response timeout.
- type
<stringstring-mdn-url> Response type. Possible values are: basic
, cors
, default
, error
, opaque
, opaqueredirect
.
- headers
<Objectobject-mdn-url> Response headers, e.g. { 'content-type': 'application/json' }
.data
any> This contains the successful response data of the user-specified type, for instance,MyReturnData
in the example shown above. Only shows when the HTTP response status code is less than400
.error
any> This contains the error response data of typeT
. Only shows when the HTTP response status code is greater than399
.
Each return type have default Generics type of
any
which means it can be any type in JavaScript and is overridable by user defined type via TypeScripttypescript-url's Generics
.// e.g. Overridable Generics
interface SuccessData {
message: string;
}
...
const d = await FetchAsJson<SuccessData>(...);
// d will have the type of `FetchAsReturnType<SuccessData, any>>`
assert(d.data.message, '...'); // OK
...
fetchAs
This contains a collection of methods that will convert the response into the specified data type:.arrayBuffer(url[, options])
Method which will return a ArrayBufferarraybuffer-mdn-url..blob(url[,options])
Method which will return a Blobblob-mdn-url..buffer(url[, options])
Method which will return a Bufferbuffer-nodejs-url..json(url[, options])
Method which will return a JSON data which can consumed by JavaScript as Objectobject-mdn-url..text(url[, options])
Method which will return a text/ string..textConverted(url[, options])
Method which will return a text/ string, except instead of always converting toUTF-8
, encoding sniffing will be performed and text converted toUTF-8
, if possible.
fetchAsArrayBuffer(url, options)
url
<stringstring-mdn-url> A string representing the URL for fetching.options
<?Objectobject-mdn-url> Options for HTTP(S) request. See@types/node-fetch
for TypeScript userstypesnode-fetch-for-typescript-users-url to see the explanation.- returns: <Promisepromise-mdn-url<FetchAsReturnTypefetchasreturntype-url<ArrayBufferarraybuffer-mdn-url>> Promise which resolves with a FetchAsReturnTypefetchasreturntype-url of type ArrayBufferarraybuffer-mdn-url.
fetchAsBlob(url, options)
url
<stringstring-mdn-url> A string representing the URL for fetching.options
<?Objectobject-mdn-url> Options for HTTP(S) request. See@types/node-fetch
for TypeScript userstypesnode-fetch-for-typescript-users-url to see the explanation.- returns: <Promisepromise-mdn-url<FetchAsReturnTypefetchasreturntype-url<Blobblob-mdn-url>> Promise which resolves with a FetchAsReturnTypefetchasreturntype-url of type Blobblob-mdn-url.
fetchAsBuffer(url, options)
url
<stringstring-mdn-url> A string representing the URL for fetching.options
<?Objectobject-mdn-url> Options for HTTP(S) request. See@types/node-fetch
for TypeScript userstypesnode-fetch-for-typescript-users-url to see the explanation.- returns: <Promisepromise-mdn-url<FetchAsReturnTypefetchasreturntype-url<Bufferbuffer-nodejs-url>> Promise which resolves with a FetchAsReturnTypefetchasreturntype-url of type Bufferbuffer-nodejs-url.
fetchAsJson(url, options)
url
<stringstring-mdn-url> A string representing the URL for fetching.options
<?Objectobject-mdn-url> Options for HTTP(S) request. See@types/node-fetch
for TypeScript userstypesnode-fetch-for-typescript-users-url to see the explanation.- returns: <Promisepromise-mdn-url<FetchAsReturnTypefetchasreturntype-url<Objectobject-mdn-url>> Promise which resolves with a FetchAsReturnTypefetchasreturntype-url of type JSON which can consumed by JavaScript as Objectobject-mdn-url.
fetchAsText(url, options)
url
<stringstring-mdn-url> A string representing the URL for fetching.options
<?Objectobject-mdn-url> Options for HTTP(S) request. See@types/node-fetch
for TypeScript userstypesnode-fetch-for-typescript-users-url to see the explanation.- returns: <Promisepromise-mdn-url<FetchAsReturnTypefetchasreturntype-url<stringstring-mdn-url>> Promise which resolves with a FetchAsReturnTypefetchasreturntype-url of type stringstring-mdn-url.
fetchAsTextConverted(url, options)
Please note that encodingencoding-url is required to be installed in order to use this method.- Identical to fetchAsText(url, options)fetchastexturl-options-url, except instead of always converting to
UTF-8
, encoding sniffing will be performed and text converted toUTF-8
, if possible.