Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fetch with progress
async function fetchWithProgress(url, opts, progressCb) {
const response = await fetch(url, opts);
let received = 0;
let contentLength = Number(response.headers.get('Content-Length')) || 0;
if (!Number.isInteger(contentLength) || !Number.isFinite(contentLength) || contentLength <= 0) {
contentLength = null;
}
return new Response(new ReadableStream({
async start(controller) {
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
progressCb(received, contentLength, true);
break;
}
received += value.byteLength;
progressCb(received, contentLength, false);
controller.enqueue(value);
}
controller.close();
},
}), {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment