Last active
June 15, 2023 14:45
-
-
Save mhazy/c1068f873cf8d59b1e0836315a1f7d96 to your computer and use it in GitHub Desktop.
Simple node service to test chunked transfer encoding
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
import http from 'node:http'; | |
// `curl -iN http://localhost:8080` | |
function sleep() { | |
return new Promise((resolve) => { | |
setTimeout(() => resolve(), 1000) | |
}); | |
} | |
async function* streamedResponse() { | |
console.log('Starting stream'); | |
for (let i = 0; i < 10; i++) { | |
yield i; | |
await sleep(); | |
} | |
console.log('Ending stream'); | |
} | |
const requestListener = async (req, res) => { | |
console.log('Doing request'); | |
res.setHeader('Content-Type', 'text/html'); | |
res.setHeader('Transfer-Encoding', 'chunked'); | |
for await (const chunk of streamedResponse()) { | |
let nextChunk = chunk.toString(); | |
console.log('Writing chunk:', nextChunk); | |
res.write(nextChunk); | |
} | |
res.end(); | |
} | |
http.createServer(requestListener).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment