Instantly share code, notes, and snippets.

Embed
What would you like to do?
document.addEventListener('DOMContentLoaded', function (e) {
var url = 'LargeFile.txt';
var progress = 0;
var contentLength = 0;
fetch(url).then(function(response) {
// get the size of the request via the headers of the response
contentLength = response.headers.get('Content-Length');
var pump = function(reader) {
return reader.read().then(function(result) {
// if we're done reading the stream, return
if (result.done) {
return;
}
// retrieve the multi-byte chunk of data
var chunk = result.value;
var text = '';
// since the chunk can be multiple bytes, iterate through
// each byte while skipping the byte order mark
// (assuming UTF-8 with single-byte chars)
for (var i = 3; i < chunk.byteLength; i++) {
text += String.fromCharCode(chunk[i]);
}
// append the contents to the page
document.getElementById('content').innerHTML += text;
// report our current progress
progress += chunk.byteLength;
console.log(((progress / contentLength) * 100) + '%');
// go to next chunk via recursion
return pump(reader);
});
}
// start reading the response stream
return pump(response.body.getReader());
})
.catch(function(error) {
console.log(error);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment