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.
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.
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)}%`);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.