Skip to content

Instantly share code, notes, and snippets.

@mhazy
Last active June 15, 2023 14:45
Show Gist options
  • Save mhazy/c1068f873cf8d59b1e0836315a1f7d96 to your computer and use it in GitHub Desktop.
Save mhazy/c1068f873cf8d59b1e0836315a1f7d96 to your computer and use it in GitHub Desktop.
Simple node service to test chunked transfer encoding
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