February 4, 2023

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

How to use fetch in node


With node 17.5.0

Use the cli flag --experimental-fetch to have it as a global.

app.js

fetch(`https://nodejs.org/en/blog/`).then(function (response) {
    if (!response.ok) {
        throw response.statusText;
    }
    return response.text();
})
.then(console.log)
.catch(console.error);

node --experimental-fetch app.js

With older version than 17.5.0

Install node-fetch

npm i node-fetch

What I like to do is having the patch in a separate file.

patch-fetch.js

import fetch from "node-fetch";


globalThis.fetch = fetch;

Then import this file in your main entry point

app.js

import "./patch-fetch.js";


Do not polyfill if fetch is already existing

patch-fetch.js

import fetch from "node-fetch";

if (!globalThis.fetch) {
    globalThis.fetch = fetch;
}

Do not polyfill and do not import if fetch is already existing

In the following example the node-fetch code is not even executed if fetch is defined.

patch-fetch.js

if (!globalThis.fetch) {
    globalThis.fetch = (await import(`node-fetch`)).default;
}

The import is inside the if statement, and it is a dynamic import.

This requires top level await and dynamic imports, so I think it is usable only in Node 16

With deno

fetch is available by default in deno



Source link