nodejs/express - stream stdout instantly to the client

前端 未结 3 482
难免孤独
难免孤独 2020-12-24 02:39

I spawned the following child: var spw = spawn(\'ping\', [\'-n\',\'10\', \'127.0.0.1\']) and I would like to receive the ping results on the client side (

3条回答
  •  星月不相逢
    2020-12-24 03:18

    This cannot be achieved with the standard HTTP request/response cycle. Basically what you are trying to do is make a "push" or "realtime" server. This can only be achieved with xhr-polling or websockets.

    Code Example 1:

    app.get('/path', function(req, res) {
       ...
       spw.stdout.on('data', function (data) {
          var str = data.toString();
          res.write(str + "\n");
       });
       ...
    }
    

    This code never sends an end signal and therefore will never respond. If you were to add a call to res.end() within that event handler, you will only get the first ping – which is the expected behavior because you are ending the response stream after the first chunk of data from stdout.

    Code Sample 2:

    spw.stdout.pipe(res);
    

    Here stdout is flushing the packets to the browser, but the browser will not render the data chunks until all packets are received. Thus the reason why it waits 10 seconds and then renders the entirety of stdout. The major benefit to this method is not buffering the response in memory before sending — keeping your memory footprint lightweight.

提交回复
热议问题