Skip to content
jshacks.dev
Async

Download files in parallel and report progress

Download files in parallel and report progress in JavaScript by reading each response body as a stream and totalling the bytes. Node.js 24.

1 min read
Summarize in AI

To show one progress bar for several downloads, read each body as a stream and add the size of every chunk to a shared total.

JavaScript
const encoder = new TextEncoder();

const makeResponse = (parts) =>
  new Response(
    new ReadableStream({
      start(controller) {
        for (const part of parts) controller.enqueue(encoder.encode(part));
        controller.close();
      },
    }),
    { headers: { 'content-length': String(parts.join('').length) } },
  );

const responses = [makeResponse(['aaaa', 'aaaa']), makeResponse(['bb', 'bb'])];
const total = responses.reduce((sum, r) => sum + Number(r.headers.get('content-length')), 0);
let loaded = 0;
const updates = [];

await Promise.all(
  responses.map(async (res) => {
    for await (const chunk of res.body) {
      loaded += chunk.length;
      updates.push(Math.round((loaded / total) * 100));
    }
  }),
);

console.log(updates.length, 'updates, last', `${updates.at(-1)}%`);
Text
4 updates, last 100%

The two fake responses stand in for fetch results. The content-length header gives the total, and every chunk read adds its length to loaded. The intermediate percentages depend on how the downloads interleave, so the example prints the number of updates and the final value. Draw the bar in the loop to see it move.

The header can be missing, or can describe the compressed size, when the server compresses the response. Then show a spinner instead of a percentage.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.