Skip to content
jshacks.dev
Node.js

How to Download a File With Node.js fetch and Streams

Stream a download to disk with fetch and pipeline in Node.js 26, check the status, show progress, resume partial files with Range and clean up after failures.

8 min read
Summarize in AI
Flat illustration of folders syncing with a cloud bucket, with the Node.js, Google Chrome, Linux, Cloudflare and DigitalOcean logos.

The shortest way to download a file with fetch is also the one that fails on large files: await response.arrayBuffer() loads the entire body into memory before you write a single byte. For a 20 MB image that is fine. For a 2 GB archive it is an out-of-memory crash, or a process that swells until the container is killed. The Response body is a web ReadableStream, and Node.js 26 can pipe it straight into a file, so memory stays flat whatever the size. This post shows the streaming download, how to check status and size first, how to report progress, how to resume with a Range request, and how to avoid leaving a half-written file behind when something goes wrong.

The memory problem, stated plainly

fetch resolves its promise as soon as the response headers arrive. The body is still on the wire. Methods such as response.json(), response.text() and response.arrayBuffer() wait for the entire body and hold it in memory. Reading the stream instead lets you handle one chunk at a time and give it to the disk, which applies backpressure to the network when the disk is slow.

The streaming download

The bridge between the web stream and a Node.js file stream is Readable.fromWeb. Then pipeline from node:stream/promises connects them and handles errors and cleanup.

download.jsJavaScript
import { createWriteStream } from "node:fs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

export async function download(url, destination) {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`Download failed: ${response.status} ${response.statusText}`);
  }
  if (!response.body) {
    throw new Error("Response has no body");
  }

  await pipeline(Readable.fromWeb(response.body), createWriteStream(destination));
}

await download("https://example.com/archive.tar.gz", "archive.tar.gz");
console.log("saved");
Text
saved

Three details are worth noticing. fetch does not reject on a 404 or 500, only on network failure, so the response.ok check is required: without it you save the error page into your archive and carry on. pipeline destroys both streams if either fails, which closes the file descriptor. And the function returns only after the file is fully flushed, because pipeline waits for the writable's finish event.

If you run this against a URL that answers with an error, the message names the status.

Text
Error: Download failed: 404 Not Found

Read the size before you commit

Headers tell you what is coming. Content-Length gives the byte size when the server knows it, and Content-Type tells you what it thinks the file is. Checking them early prevents filling a disk with something unexpected.

guarded.jsJavaScript
import { createWriteStream } from "node:fs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

const MAX_BYTES = 500 * 1024 * 1024;

export async function downloadGuarded(url, destination) {
  const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);

  const length = Number(response.headers.get("content-length"));
  if (length && length > MAX_BYTES) {
    await response.body.cancel();
    throw new Error(`File too large: ${length} bytes`);
  }

  await pipeline(Readable.fromWeb(response.body), createWriteStream(destination));
  return { bytes: length || null, type: response.headers.get("content-type") };
}

response.body.cancel() tells the connection to stop, so the rest of a rejected file is not transferred. The AbortSignal.timeout(60_000) aborts the request after 60 seconds, but note what it covers: it also applies while the body streams, so a slow but healthy 600 MB download can hit the limit. For big files use a longer value, or an AbortController that you reset on each chunk to measure inactivity, not total time.

A missing Content-Length is common, for example with chunked encoding or compressed responses, so you cannot rely on it as a limit. Count bytes as they pass if the limit must be firm.

Show progress

To report progress, put a Transform in the pipeline that counts bytes. It passes every chunk through unchanged.

progress.jsJavaScript
import { createWriteStream } from "node:fs";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";

export async function downloadWithProgress(url, destination) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);

  const total = Number(response.headers.get("content-length")) || 0;
  let received = 0;
  let lastPrinted = -1;

  const counter = new Transform({
    transform(chunk, _encoding, callback) {
      received += chunk.length;
      if (total) {
        const percent = Math.floor((received / total) * 100);
        if (percent !== lastPrinted && percent % 10 === 0) {
          lastPrinted = percent;
          console.log(`${percent}%`);
        }
      }
      callback(null, chunk);
    },
  });

  await pipeline(Readable.fromWeb(response.body), counter, createWriteStream(destination));
  return received;
}

const bytes = await downloadWithProgress("https://example.com/video.mp4", "video.mp4");
console.log(`done, ${bytes} bytes`);

For a file of 12,582,912 bytes with a known length, the output steps through the milestones.

Text
0%
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
done, 12582912 bytes

Printing only when the percentage crosses a multiple of ten matters more than it looks: a callback that logs on every chunk produces thousands of lines and can slow the download itself. If the length is unknown, report bytes received instead of a percentage.

Resume a partial download

Servers that advertise Accept-Ranges: bytes let you ask for the rest of a file. If a download dies at byte 4,000,000, you can restart from there and append.

resume.jsJavaScript
import { createWriteStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

export async function downloadResumable(url, destination) {
  let offset = 0;
  try {
    offset = (await stat(destination)).size;
  } catch {
    offset = 0;
  }

  const headers = offset > 0 ? { range: `bytes=${offset}-` } : {};
  const response = await fetch(url, { headers });

  if (response.status === 416) return "already complete";
  if (offset > 0 && response.status === 200) {
    offset = 0;
  } else if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  const flags = offset > 0 ? "a" : "w";
  await pipeline(Readable.fromWeb(response.body), createWriteStream(destination, { flags }));
  return offset > 0 ? `resumed at ${offset}` : "downloaded";
}

The status code tells you what the server did. 206 Partial Content means it honored the range and sent only the rest, so you append. 200 OK after you asked for a range means the server ignored the header and sent the whole file, so you must start over with the w flag, which the code does by resetting offset. 416 Range Not Satisfiable usually means the file on disk is already as large as the remote one. A resumed run on a file that stopped at 4,000,000 bytes returns:

Text
resumed at 4000000

One caution: resuming assumes the remote file did not change between attempts. For anything that matters, send an If-Range header with the ETag you saved from the first response, so the server falls back to a full download if the content changed. And verify the result with a checksum when the publisher provides one.

Never leave a half-written file in the final place

If the connection drops at 70 percent, pipeline rejects, and the partial file stays on disk under the final name. A later step sees the file exist and treats it as complete. The fix is to write to a temporary name and rename on success.

atomic.jsJavaScript
import { createWriteStream } from "node:fs";
import { rename, rm } from "node:fs/promises";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

export async function downloadAtomic(url, destination) {
  const temp = `${destination}.part`;
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);

  try {
    await pipeline(Readable.fromWeb(response.body), createWriteStream(temp));
    await rename(temp, destination);
  } catch (error) {
    await rm(temp, { force: true });
    throw error;
  }
}

rename within one file system is atomic, so readers see either no file or the whole one. The .part suffix also makes abandoned downloads easy to find and delete. If you combine this with resuming, keep the .part file between attempts instead of removing it in the catch block, and only remove it on errors you cannot recover from.

Writing to a stream you already have

Not every download goes to disk. You can pipe the same body into a hash, a decompressor or an HTTP response of your own, and the memory behavior stays flat.

hash-download.jsJavaScript
import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

const response = await fetch("https://example.com/archive.tar.gz");
const hash = createHash("sha256");

await pipeline(Readable.fromWeb(response.body), hash);
console.log(hash.digest("hex"));
Text
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

The digest above is an example value. Hashing while you stream means you verify a file without reading it twice, and you can compare against the publisher's checksum before you ever extract it. The same pattern works with zlib.createGunzip() in the middle to unpack on the fly.

Handling redirects, proxies and compression

Most real downloads are not a single clean request. Release assets and storage links usually answer with a 302 that points at a signed URL, and fetch follows redirects by default, up to 20 of them. That is what you want, with one caution: the Authorization header is dropped when a redirect crosses to a different origin, which is correct for security and a surprise when a private download then answers 403. If you need to send credentials to the final host, make the first request with redirect: "manual", read the Location header and issue a second request yourself.

Compression is a second source of confusion. fetch in Node.js asks for compressed responses and decompresses them transparently, so Content-Length describes the compressed bytes while the stream you read is the decompressed data. For a .tar.gz file served as a plain binary there is no transparent decoding, since the server sends no Content-Encoding, but a file the server compresses on the fly reports a length that does not match what you write. Use the length only as a hint for progress, and never to check integrity, which is the job of a checksum.

Corporate proxies are the third. Node.js fetch does not read the HTTPS_PROXY variable on its own unless you enable it, so a download that works in curl can hang in a script on a machine behind a proxy. Check the current documentation for the proxy options in your release before debugging the network.

Also inBrowser
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.