We want to stream JSON/text data from the server to the browser in chunks, with a short delay between each chunk — without needing the full response to be prepared up front.
This is perfect for:
- Real-time logs
- Progressive data loading
- Simulating live data feeds
Instead of sending all data at once, we use:
Transfer-Encoding: chunkedThis tells the browser:
“I'm sending data in parts. Keep listening — more will come.”
By setting this header, the server tells the client: "Data will come in pieces."
res.writeHead(200, {
'Content-Type': 'application/json',
'Transfer-Encoding': 'chunked',
});We simulate live data by sending one chunk every 2 seconds using setInterval():
const interval = setInterval(() => {
res.write(`💡 Chunk ${count} sent at ${count * 2}s\n`);
}, 2000);Once we’re done sending all chunks, we clean up and tell the browser we’re finished:
res.write('🟢 All chunks sent.\n');
res.end();Chunked transfer is great when:
- You don’t know the full response size in advance
- You want to stream progressively
- You’re mimicking a live data source
It helps the browser or client:
- Show real-time updates without reloading
- Handle large datasets without waiting for everything
✅ Real-time analytics dashboards
✅ Server log viewers
✅ Long-running API responses
✅ Chat messages and notifications