Binary stream example using Fetch
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
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<title>Binary streaming using Fetch</title> | |
</head> | |
<body> | |
<h1>Binary streaming using Fetch</h1> | |
<img src=""> | |
<script> | |
let data = [] | |
const processing = function (done, value) { | |
if (done) { | |
const img = new Blob(data, { type: 'image/png' }) | |
document.querySelector('img').setAttribute('src', URL.createObjectURL(img)) | |
return | |
} | |
// doing something with the data... | |
data.push(value) | |
} | |
const url = 'https://loremflickr.com/1200/720/nature' | |
const req = new Request(url) | |
console.log('loading...') | |
fetch(req) | |
.then(response => { | |
const reader = response.body.getReader(); | |
const reading = function ({done, value}) { | |
if (!done) { | |
console.log('chunk loaded, size:', value.length) | |
processing(false, value) | |
reader.read().then(reading) | |
} else { | |
console.log('loaded!') | |
processing(true) | |
} | |
} | |
reader.read().then(reading) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment