Node 18 Fetch Download [better] File < PRO >

: Retrieve the total file size from the headers.

async function downloadWithProgress(url, outputPath) { const response = await fetch(url); const totalBytes = parseInt(response.headers.get('content-length'), 10); let receivedBytes = 0; const reader = response.body.getReader(); const fileStream = fs.createWriteStream(outputPath); while (true) { const { done, value } = await reader.read(); if (done) break; receivedBytes += value.length; fileStream.write(value); const percentage = ((receivedBytes / totalBytes) * 100).toFixed(2); console.log(`Progress: ${percentage}% (${receivedBytes}/${totalBytes} bytes)`); } fileStream.end(); } Use code with caution. Key Comparison: Native Fetch vs. Older Methods node 18 fetch download file

With the release of , developers can finally use the native fetch API without installing third-party libraries like node-fetch or axios . Downloading files with this native tool is efficient and memory-friendly when paired with Node's streaming capabilities. Standard Stream Download (The Efficient Way) : Retrieve the total file size from the headers

import fs from 'node:fs'; import { Readable } from 'node:stream'; import { finished } from 'node:stream/promises'; async function downloadFile(url, outputPath) { const response = await fetch(url); if (!response.ok) { throw new Error(`Failed to fetch: ${response.statusText}`); } // Node 18 native fetch uses Web Streams; convert to Node Readable stream const fileStream = fs.createWriteStream(outputPath); await finished(Readable.fromWeb(response.body).pipe(fileStream)); console.log('Download complete!'); } downloadFile('https://example.com', './my-image.png'); Use code with caution. Advanced: Tracking Download Progress Older Methods With the release of , developers

How can I download and save a file using the Fetch API? (Node.js)