简体   繁体   中英

How to send real time stream response from server to client using Node.js express

on post request server is generating data after every few seconds, these are almost 1000 to 10000 entries. Currently i'm saving data into csv file with createWriteStream and it's working fine. how can i pass data to client.

Name and Age variable getting data after few seconds

app.post('/', (req, res) => {

// currently passing to results.csv. its working fine i want to send this real time (Name and age) data to client.

const stream = createWriteStream('./results.csv', { flags: 'a', encoding: 'utf8' })

 // Append evaluation from response to file

 stream.write(`${Name}, ${Age}\n`)

// example data:  Patrick, 32

// End stream to avoid accumulation

 stream.end()
})

res.send() only send first entry but Name and age variable getting update after after each 10 seconds

app.listen(port, () => {
 console.log("App is running on port " + port);
}); 

The Express's Response is actually a steam !

So using this you can send response chunk by chunk:

res.write(chunk);

And to end the response:

res.end();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM