Skip to main content

Node Fetch Download File Better [ TRENDING · 2026 ]

This example uses the stream/pipeline utility, which is the safest way to handle streams because it automatically cleans up and handles errors for you. javascript

: This version is ESM-only . You must use import rather than require() . It is designed to be more compliant with the browser's WHATWG Fetch Standard.

For large files, you should never load the entire file into memory (e.g., using response.arrayBuffer() ). Instead, stream the data directly to your disk using fs.createWriteStream . This keeps your memory usage low and stable. node fetch download file

The implementation details change slightly depending on your version of node-fetch .

import fetch from 'node-fetch'; import { createWriteStream } from 'fs'; import { pipeline } from 'stream/promises'; async function downloadFile(url, outputPath) { const response = await fetch(url); if (!response.ok) { throw new Error(`Failed to fetch ${url}: ${response.statusText}`); } // response.body is a Node.js Readable stream in node-fetch await pipeline(response.body, createWriteStream(outputPath)); console.log('Download complete!'); } downloadFile('https://example.com', './local-image.png') .catch(console.error); Use code with caution. 2. Version Differences: v2 vs. v3 This example uses the stream/pipeline utility, which is

: Check response.headers.get('content-length') to get the total file size.

While native fetch is now stable in Node.js v21+, node-fetch remains a popular choice for older environments or specific middleware needs. 1. The Streaming Approach (Best for Large Files) It is designed to be more compliant with

Downloading files with node-fetch is a common task in Node.js applications, but the "best" way to do it depends on whether you are using the older or the modern v3+ (ESM) .

: In both versions, response.body provides a stream, but in v3, you may need to ensure compatibility between "Web Streams" and "Node Streams" depending on your Node version. 3. Handling Small Files (Simple Method)

: This version is CommonJS . If your project still uses require() , you should stick with v2.