Skip to content

Instantly share code, notes, and snippets.

@connorjclark
Last active May 9, 2022 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save connorjclark/6afb9fb588331a23a2d8fa57cfefe8f5 to your computer and use it in GitHub Desktop.
Save connorjclark/6afb9fb588331a23a2d8fa57cfefe8f5 to your computer and use it in GitHub Desktop.
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