Last active
April 27, 2018 13:56
Star
You must be signed in to star a gist
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(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