Skip to content

Instantly share code, notes, and snippets.

@kypflug
Created May 24, 2016 00:38
Show Gist options
  • Save kypflug/f3d19ab442f3732d12ee8d79b6a60ca3 to your computer and use it in GitHub Desktop.
Save kypflug/f3d19ab442f3732d12ee8d79b6a60ca3 to your computer and use it in GitHub Desktop.
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