Skip to main content
7 of 12
added 10 characters in body
Mike 'Pomax' Kamermans
  • 54.3k
  • 17
  • 134
  • 182

Late 2022 edit:

Node v18 and on come with native Fetch API support built right into Node itself. No need for third party libraries or small hand-crafted shims, just use fetch the way you're used to from the browser.

Original answer:

For Node with Promise support, a simple Node shim for (part of) the Fetch API requires only a smattering of extra code, rather than needing to install any special modules:

const http = require(`http`); const https = require(`https`); module.exports = function fetch(url) { // we're returning a promise, so this function can also be `await`ed return new Promise((resolve, reject) => { const data = []; // make sure we use the correct protocol handler const client = url.startsWith("https") ? https : http; client .request(url, (conn) => { // aggregate the response stream into a single string. conn.on(`data`, (chunk) => data.push(chunk)); conn.on(`end`, () => { // make sure to encode that string using utf8 const asBytes = Buffer.concat(data); const asString = asBytes.toString(`utf8`); // and then trigger the resolution, with the // most frequently used fetch API "follow-up" // functions: resolve({ arrayBuffer: async () => asBytes, json: async () => JSON.parse(asString), text: async () => asString, }); }); conn.on(`error`, (e) => reject(e)); }) .end(); }); }; 

Which you can then use for whatever you need, using the normal fetch syntax you're used to from the browser:

const fs = require(`fs`); const fetch = require(`./that-code-shown-above.js`); fetch(`https://placekitten.com/200/300`) .then(res => res.arrayBuffer()) .then(bytes => fs.writeFileSync(`kitten.jpg`, bytes)) .catch(e => console.error(e)); try { const response = await fetch(`https://jsonplaceholder.typicode.com/todos/1`); const data = await response.json(); console.log(data); } catch (e) { console.error(e); } // etc. 
Mike 'Pomax' Kamermans
  • 54.3k
  • 17
  • 134
  • 182