Socket
Socket
Sign inDemoInstall

node-fetch

Package Overview
Dependencies
3
Maintainers
1
Versions
96
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    node-fetch

A light-weight module that brings window.fetch to node.js


Version published
Maintainers
1
Install size
415 kB
Created

Package description

What is node-fetch?

The node-fetch package is a light-weight module that brings window.fetch to Node.js. It is designed to provide a fetch-first, URL-friendly way to access resources across the network.

What are node-fetch's main functionalities?

Simple GET Request

This code performs a simple GET request to the GitHub API and logs the response data.

const fetch = require('node-fetch');

fetch('https://api.github.com/users/github')
  .then(response => response.json())
  .then(data => console.log(data));

POST Request with JSON

This code sends a POST request with a JSON body to httpbin.org and logs the response JSON.

const fetch = require('node-fetch');

fetch('https://httpbin.org/post', {
  method: 'post',
  body:    JSON.stringify({foo: 'bar'}),
  headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));

Handling Network Errors

This code attempts to fetch a resource from an invalid domain and catches network errors.

const fetch = require('node-fetch');

fetch('https://domain.invalid')
  .catch(err => console.error('Network error:', err));

Stream Response

This code fetches an image from GitHub and streams it to a file.

const fetch = require('node-fetch');
const fs = require('fs');

fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
  .then(res => {
    const dest = fs.createWriteStream('./octocat.png');
    res.body.pipe(dest);
  });

Other packages similar to node-fetch

Readme

Source

node-fetch

npm version build status coverage status

A light-weight module that brings window.fetch to node.js

Motivation

I really like the notion of Matt Andrews' isomorphic-fetch: it bridges the API gap between client-side and server-side http requests, so developers have less to worry about.

But I think the term isomorphic is generally misleading: it gives developers a false sense of security that their javascript code will run happily on both controlled server environment as well as uncontrollable user browsers. When the latter is only true for a subset of modern browsers, not to mention quirks in native implementation.

Instead of implementing XMLHttpRequest in node to run browser-specific fetch polyfill, why not go from node's http to fetch API directly? Node has native stream support, browserify build targets (browsers) don't, so underneath they are going to be vastly different anyway.

Hence node-fetch, minimal code for a window.fetch compatible API on node.js runtime.

Features

  • Stay consistent with window.fetch API.
  • Make conscious trade-off when following whatwg fetch spec and stream spec implementation details, document known difference.
  • Use native promise, but allow substituting it with [insert your favorite promise library].

Difference from client-side fetch

  • See Known limits for details.
  • If you happen to use a missing feature that window.fetch offers, feel free to open an issue.
  • Pull requests are welcomed too!

Install

npm install node-fetch --save

Usage

var fetch = require('node-fetch');

// plain text or html

fetch('https://github.com/')
	.then(function(res) {
		return res.text();
	}).then(function(body) {
		console.log(body);
	});

// json

fetch('https://api.github.com/users/github')
	.then(function(res) {
		return res.json();
	}).then(function(json) {
		console.log(json);
	});

// meta

fetch('https://github.com/')
	.then(function(res) {
		console.log(res.status);
		console.log(res.statusText);
		console.log(res.headers.raw());
		console.log(res.headers.get('content-type'));
	});

// post

fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' })
	.then(function(res) {
		return res.json();
	}).then(function(json) {
		console.log(json);
	});

// post with stream from resumer

var resumer = require('resumer');
var stream = resumer().queue('a=1').end();
fetch('http://httpbin.org/post', { method: 'POST', body: stream })
	.then(function(res) {
		return res.json();
	}).then(function(json) {
		console.log(json);
	});

// post with form-data

var FormData = require('form-data');
var form = new FormData();
form.append('a', 1);
fetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })
	.then(function(res) {
		return res.json();
	}).then(function(json) {
		console.log(json);
	});

// node 0.11+, yield with co

var co = require('co');
co(function *() {
	var res = yield fetch('https://api.github.com/users/github')
		.then(function(res) {
			return res.json();
		}).then(function(json) {
			console.log(json);
		});

	console.log(res);
});

See test cases for more examples.

License

MIT

Acknowledgement

Thanks to github/fetch for providing a solid implementation reference.

Keywords

FAQs

Last updated on 27 Jan 2015

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc