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

Issue

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);
}); 

Solution

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();

Answered By – Positivity

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published