Skip to content

Instantly share code, notes, and snippets.

@ka2n
Created January 20, 2023 02:30
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 ka2n/52c7bcef8bc70eb560e4a8531a29d49c to your computer and use it in GitHub Desktop.
Save ka2n/52c7bcef8bc70eb560e4a8531a29d49c to your computer and use it in GitHub Desktop.
Read streaming response with fetch
const http = require('http')
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html')
res.setHeader('Transfer-Encoding', 'chunked');
res.send(`<html><body><h1>Hello World</h1>
<ul id="list"></ul>
<script>
fetch('/stream').then(res => {
const reader = res.body.getReader()
const decoder = new TextDecoder('utf-8')
reader.read().then(function processResult(result) {
if (result.done) return
const chunk = decoder.decode(result.value)
const li = document.createElement('li')
li.textContent = chunk
document.getElementById('list').appendChild(li)
return reader.read().then(processResult)
})
})
</script>
</body></html>`)
})
app.get('/stream', (req, res) => {
res.setHeader('Content-Type', 'text/plain')
res.setHeader('Transfer-Encoding', 'chunked');
res.write('Hello')
streamResponse(res, 0)
})
const streamResponse = (res, num) => {
if (num > 10) {
console.log('end')
res.end()
return
}
res.write(`Hi! part ${num}`)
setTimeout(() => streamResponse(res, num + 1), 1000)
}
http.createServer(app).listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment