1.0.1 • Published 1 year ago
@systemsoftware/fetch v1.0.1
@systemsoftware/fetch
Simple Promise-based HTTP client for Node.js
Features
- Promise-based
- Simple API that's similar to the Fetch API
- Supports the full Request API
- Supports the full Headers API
- Powered by the built-in http and https modules
- Supports chunked responses
- Supports JSON, ArrayBuffer, Blob, FormData, and text responses
- Supports AbortController, AbortSignal, and timeout
- ESM and CommonJS support
- Lightweight and zero dependencies
Table of Contents
Installation
npm install @systemsoftware/fetchUsage
Basic
Where METHOD is one of the following: get, post, put, delete, head, patch.
const fetch = require('@systemsoftware/fetch');
fetch.METHOD('https://example.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));fetch
const { fetch } = require('@systemsoftware/fetch');
fetch('https://example.com', { method: 'GET' })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));Request Support
const req = new Request('https://example.com', { method: 'GET', headers:new Headers({ 'Content-Type': 'application/json' }) });
fetch(req)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));Silence Errors
By default, @systemsoftware/fetch will throw an error if the response status code is not in the range 200-299. To silence these errors, you can use the silent option and the response will be returned regardless of the status code.
const { fetch } = require('@systemsoftware/fetch');
fetch('https://example.com', { method: 'GET', silent: true })
.then(response => response.json())
.then(data => console.log(data))AbortController
To abort a request, you can use the AbortController class.
const { fetch } = require('@systemsoftware/fetch');
const controller = new AbortController();
fetch('https://example.com', { method: 'GET', signal: controller.signal })
controller.abort();onData
To handle the response data in chunks, you can use the onData option.
const { fetch } = require('@systemsoftware/fetch');
fetch('https://example.com', { method: 'GET', onData: chunk => console.log(chunk) })
.then(response => console.log('Response finished'))
.catch(error => console.error(error));Response
The response object is what is returned by the http request, with these additional methods:
json- A promise that returns the response body as JSONtext- A promise that returns the response body as textarrayBuffer- A promise that returns the response body as an ArrayBufferblob- A promise that returns the response body as a Blob