Package Exports
- fetch-as
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (fetch-as) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
fetch-as
Fetch data in Node.js
Fetch API in Node.js with specific response type
Table of contents
Pre-requisites
Setup
Install
# Install via NPM
$ npm install --save fetch-asUsage
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();Native ES modules or TypeScript
/**
* 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();@types/node-fetch for TypeScript users
For TypeScript users, you are recommended to install the required typing file from @types/node-fetch 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 Options for a list of supported options.
$ npm install --dev @types/node-fetchAPI Reference
FetchAsInfo
// Interface
{
size: number;
timeout: number;
type: "basic"|"cors"|"default"|"error"|"opaque"|"opaqueredirect";
headers: {
[key: string]: any;
};
}FetchAsReturnType
// Interface
{
status: number;
info: FetchAsInfo; // See `FetchAsInfo`.
data?: any;
error?: any;
}FetchAsData<T>
Response data returned in the type of T that extends FetchAsReturnType by default where data and error is of type any and this is overridable by the user to decide what it returns. To do so, user can create interfaces in TypeScript like so:
declare interface MyReturnData {
message: string;
}
declare interface MyReturnError {
type: string;
message: string;
}
declare interface MyReturnType extends FetchAsReturnType {
data?: MyReturnData;
error?: MyReturnError;
}
import { FetchAsReturnType } from 'fetch-as';
import { fetchAsJson } from 'fetch-as';
async function main() {
const url = 'https://your-domain.com';
const d = await fetchAsJson<MyReturnType>(url);
assert(d.data.message, 'OK'); // OK
}
main();status<string> HTTP response status code. Any response that has a HTTP status greater than399can be regarded as an error response.data<?Object|Buffer|string> This contains the successful response data of the user-specified type, for instance,MyReturnDatain the example shown above. Only shows when the HTTP response status code is less than400.error<?Object|Buffer|string> This contains the error response data of typeT. Only shows when the HTTP response status code is greater than399.info<Object> This contains additional information you might need from a response. See FetchAsInfo for the detailed interface.
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 ArrayBuffer..blob(url[,options])Method which will return a Blob..buffer(url[, options])Method which will return a Buffer..json(url[, options])Method which will return a JSON data which can consumed by JavaScript as Object..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<string> A string representing the URL for fetching.options<?Object> Options for HTTP(S) request. See@types/node-fetchfor TypeScript users to see the explanation.- returns: <Promise<FetchAsData<ArrayBuffer>> Promise which resolves with a FetchAsData of type ArrayBuffer.
fetchAsBlob(url[, options])
url<string> A string representing the URL for fetching.options<?Object> Options for HTTP(S) request. See@types/node-fetchfor TypeScript users to see the explanation.- returns: <Promise<FetchAsData<Blob>> Promise which resolves with a FetchAsData of type Blob.
fetchAsBuffer(url[, options])
url<string> A string representing the URL for fetching.options<?Object> Options for HTTP(S) request. See@types/node-fetchfor TypeScript users to see the explanation.- returns: <Promise<FetchAsData<Buffer>> Promise which resolves with a FetchAsData of type Buffer.
fetchAsJson(url[, options])
url<string> A string representing the URL for fetching.options<?Object> Options for HTTP(S) request. See@types/node-fetchfor TypeScript users to see the explanation.- returns: <Promise<FetchAsData<Object>> Promise which resolves with a FetchAsData of type JSON which can consumed by JavaScript as Object.
fetchAsText(url[, options])
url<string> A string representing the URL for fetching.options<?Object> Options for HTTP(S) request. See@types/node-fetchfor TypeScript users to see the explanation.- returns: <Promise<FetchAsData<string>> Promise which resolves with a FetchAsData of type string.
fetchAsTextConverted(url[, options])
* Please note that encoding is required to be installed in order to use this method.
- Identical to fetchAsText(url[, options]), except instead of always converting to
UTF-8, encoding sniffing will be performed and text converted toUTF-8, if possible.
License
MIT License © Rong Sen Ng