Skip to content

Instantly share code, notes, and snippets.

@necccc
Created January 25, 2018 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save necccc/41132d9303a31644536f639e924d15b7 to your computer and use it in GitHub Desktop.
Save necccc/41132d9303a31644536f639e924d15b7 to your computer and use it in GitHub Desktop.
Binary stream example using Fetch
<!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