Elson D'Sa
Elson D'Sa

Reputation: 109

How to send multiple responses from Node js using res.write, so that the data appears live in the client?

I want to send data immediately to the client from res.write, but the data is being sent exactly once in one response. How can i send multiple responses so the data is sent live to the client?

app.get('/api/simulator', (req,res) => {


    res.setHeader('Content-Type','text/html');
    var spawn = require('child_process').spawn,
ls = spawn('../abc.sh');

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
  res.write(data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
    console.log('child process exited with code ' + code.toString());
    res.end();
  });

    });

Upvotes: 1

Views: 574

Answers (1)

Tri Bui Quang
Tri Bui Quang

Reputation: 59

I think you just add another line res.write(): - Example:

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
  res.write(data.toString());
  response.write("foo");
  response.write("bar");
});

Upvotes: 0

Related Questions