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

Time:08-08

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

CodePudding user response:

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