Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adds an onProgress mechanism to track Download Progress when using the `fetch` API.
function progressHelper(onProgress) {
return response => {
if (!response.body) return response
// ^ preventable failure: throw new Error('ReadableStream unsupported in your browser.');
const contentLength = response.headers.get('content-length')
if (!contentLength) return response
// ^ preventable failure: throw new Error('Content-Length header missing')
const total = parseInt(contentLength, 10)
let loaded = 0
return new Response(
new ReadableStream({
start(controller) {
const reader = response.body.getReader()
return read()
function read() {
return reader
.read()
.then(({ done, value }) => {
if (done) {
controller.close()
return;
}
loaded += value.byteLength
onProgress({ loaded, total })
controller.enqueue(value)
return read()
})
.catch(error => {
console.error(error)
controller.error(error)
})
}
},
})
)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment