-
-
Save connorjclark/6afb9fb588331a23a2d8fa57cfefe8f5 to your computer and use it in GitHub Desktop.
Fetch with progress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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