Fetch Streaming Response Backpressure
Read a fetch response body as a stream with manual reader control, honoring backpressure so a slow consumer cannot balloon memory.
Code
// stream the response body incrementally so backpressure applies
async function downloadWithProgress(url, onProgress, chunkPauseMs = 0) {
const res = await fetch(url);
if (!res.ok || !res.body) throw new Error('download failed: ' + res.status);
const total = Number(res.headers.get('content-length') ?? 0);
const reader = res.body.getReader();
let received = 0;
const parts = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
parts.push(value);
received += value.length;
if (onProgress && total > 0) {
onProgress(received, total);
}
if (chunkPauseMs > 0) {
// 消费变慢时读取循环自然放慢,读取暂停即向上游传导背压
await new Promise((r) => setTimeout(r, chunkPauseMs));
}
}
const blob = new Blob(parts);
return { bytes: received, total, blob };
}
const result = await downloadWithProgress(
'https://cdn.example.com/dataset.bin',
(got, total) => console.log('progress:', Math.round((got / total) * 100) + '%'),
10,
);
console.log('downloaded', result.bytes, 'of', result.total, 'bytes');Inside the snippet
Count the function downloadWithProgress as the entire surface area of Fetch Streaming Response Backpressure.
One loop does the cycling here: while (true). The asynchronous flow is linearized with await, keeping failure handling local. Error is the guard’s signal — thrown at the branch, before any partial work happens.
The result comes back as an object carrying received, total.
Watch out for
fetchexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!res.ok || !res.bodyshort-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
Entry signature: async function downloadWithProgress(url, onProgress, chunkPauseMs = 0)
Running the file prints labeled results such as progress:, downloaded — each operation’s effect is visible in the output.
The call returns received, total — destructure what you need at the call site.
Core lines
await new Promise((r) => setTimeout(r, chunkPauseMs));
if (!res.ok || !res.body) throw new Error('download failed: ' + res.status);
const total = Number(res.headers.get('content-length') ?? 0);
Interactive Tools for This Topic
FAQ
- Does `downloadWithProgress` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- How does the code behave when input is bad?
- The code throws `Error` — the guard `!res.ok || !res.body` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `downloadWithProgress` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.