1

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

    });
3
  • There can only be a single response to a single request, you will have to make multiple requests for multiple responses. The better solution is to use Socket.io for streaming. Commented Apr 3, 2020 at 5:29
  • The problem is that, in nearly all cases, the browser is waiting for the completion of the http request before it will display anything or return anything to the ajax call. So, even though you may be incrementally sending data with res.write(), the client in the browser typically won't show the data until it has all arrived. If you can be more specific about exactly what you're trying to do, perhaps we could help in more detail. A webSocket connection would allow you to send individual chunks of data that would be received by the client immediately. Commented Apr 3, 2020 at 6:03
  • Documentation . You can add res.write successively. Commented May 19, 2021 at 21:33

1 Answer 1

0

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");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.