Skip to content

Instantly share code, notes, and snippets.

@justsml
Last active February 10, 2019 22:25
Show Gist options
  • Save justsml/a8ffd810fc7e5a5295dfc898302ddbfc to your computer and use it in GitHub Desktop.
Save justsml/a8ffd810fc7e5a5295dfc898302ddbfc to your computer and use it in GitHub Desktop.
Adds an onProgress mechanism to track Download Progress when using the `fetch` API.
function progressHelper(onProgress) {
return (response) => {
if (!response.body) return response
let loaded = 0
const contentLength = response.headers.get('content-length')
const total = !contentLength ? -1 : parseInt(contentLength, 10)
return new Response(
new ReadableStream({
start(controller) {
const reader = response.body.getReader()
return read()
function read() {
return reader.read()
.then(({ done, value }) => {
if (done) return void controller.close()
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