node-fetch brings the Fetch API to Node.js. While Node 18+ has built-in fetch, node-fetch remains relevant for older versions and offers additional features like custom agents and AbortController integration.
Installation
npm install node-fetch
Basic Usage
import fetch from "node-fetch";
// GET request
const response = await fetch("https://api.github.com/users/node-fetch");
const data = await response.json();
console.log(data);
// POST with JSON
const result = await fetch("https://httpbin.org/post", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tool: "node-fetch", version: 3 })
});
console.log(await result.json());
Handling Streams
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
const response = await fetch("https://example.com/large-file.zip");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
await pipeline(response.body, createWriteStream("download.zip"));
console.log("Download complete");
Request Cancellation
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch("https://api.example.com/slow", {
signal: controller.signal
});
const data = await response.json();
console.log(data);
} catch (err) {
if (err.name === "AbortError") {
console.log("Request timed out");
}
} finally {
clearTimeout(timeout);
}
Custom HTTP Agent
import https from "node:https";
const agent = new https.Agent({
keepAlive: true,
maxSockets: 10
});
const response = await fetch("https://api.example.com/data", { agent });
Form Data Upload
import { FormData, File } from "node-fetch";
import { readFileSync } from "node:fs";
const form = new FormData();
form.append("field", "value");
form.append("file", new File([readFileSync("photo.jpg")], "photo.jpg", { type: "image/jpeg" }));
const response = await fetch("https://httpbin.org/post", {
method: "POST",
body: form
});
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)