Skip to content

Instantly share code, notes, and snippets.

@rlemon
Last active April 27, 2018 13:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rlemon/e5446ff5ba8b5a80f6c51aa946962513 to your computer and use it in GitHub Desktop.
fetch with progress
async function fetchWithProgress(file, options = {}, progressUpdate = null) {
try {
const fileResponse = await fetch(file, options);
const totalBytes = fileResponse.headers.get('content-length');
// if there is no content length, we can't calculate any progress.
// also if there is no provided callback, there is no point.
if( totalBytes === null || progressUpdate === null ) {
if( totalBytes === null ) console.error('content-length not available');
return fileResponse;
}
const fileReader = fileResponse.body.getReader();
let currentBytes = 0;
const stream = new ReadableStream({
async start(controller) {
try {
while( true ) {
const { done, value } = await fileReader.read();
if( done ) {
break;
}
currentBytes += value.length;
controller.enqueue(value);
progressUpdate(currentBytes/totalBytes);
}
controller.close();
fileReader.releaseLock();
} catch( error ) {
console.error(error);
}
}
});
const streamResponse = new Response(stream);
return streamResponse;
} catch( error ) {
console.error(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment