I am trying to emit chunks of data with a Node.js endpoint, the goal is to display it dynamically with curl. But when I use curl -X GET , nothing is displayed until everything is displayed all at once (I want the output to be dynamic, not just everything at the end). I also tried with a python flask streaming server and it works, so I guess the issue has something to do with Node.js.
Below my code :
app.get('/stream', (req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
const responseChunks = [
"Hello,",
"how are you",
"...\n"
];
let chunkIndex = 0;
// Send data every 500ms
const intervalId = setInterval(() => {
if (chunkIndex < responseChunks.length) {
res.write(responseChunks[chunkIndex]);
chunkIndex++;
} else {
clearInterval(intervalId);
res.end();
}
}, 500);
req.on('close', () => {
clearInterval(intervalId);
console.log('Stream stopped.');
});
});
...
https.createServer(credentials, app).listen(443, '0.0.0.0', () => {
console.log(`HTTPS Server is running on :443`);
});
I already checked How do I stream response in express?, but I got the same problem, the result in curl command is displayed at the end, I want the output to be dynamic.