It is possible on Express.js
to send a response in chunk of data? I have tried (online demo):
const express = require('express');
const app = express();
const port = 3111;
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
app.get('/', async (req, res) => {
res.setHeader('Content-Type', 'application/json');
// flush to enable stream
res.flushHeaders();
res.write('[');
for (let i = 1; i <= 1000; i++) {
res.write(JSON.stringify(`data ${i}`));
if (i + 1 <= 1000) {
res.write(',');
}
await sleep(1);
}
res.write(']');
res.end();
});
app.listen(port, () => {
console.log(`App is live at http://localhost:${port}`);
});
But both on Google Chrome and Postman, the response is showed only when res.end()
is called
2
Answers
There are some considerations
Content-Type
for streams such asapplication/stream+json
res.flushHeaders()
asExpress
automatically handle it when you start writing the response bodyUsing
netcat
, the pacing of data returned seems correct, and it’s chunk encoded.Sample of output: