11
votes

I'm trying to capture the stdout from a spawned child_process in node.js (0.10.29).

Right now I'm just trying with ping

The following code doesn't print (but does ping)

var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var util = require('util')

var ping = spawn('ping', ['127.0.0.1'], {stdio: 'pipe'});

ping.stdout.on('data', function(data){
    util.print(data);
})

ping.stderr.on('data', function(data){
    util.print(data);
})

If I change stdio: 'pipe' to stdio: 'inherit' and get rid of the stdout/stderr hooks like so:

var ping = spawn('ping', ['127.0.0.2'], {stdio: 'inherit'});

// ping.stdout.on('data', function(data){
//  util.print(data);
// })

// ping.stderr.on('data', function(data){
//  util.print(data);
// })

I get

PING 127.0.0.2 (127.0.0.2): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1

If I change the address from 127.0.0.2 to 127.0.0.1, which I know will respond to the pings and use the original code I get

PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.060 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.063 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.152 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.124 ms

Any ideas why stdout/stderr are not firing data events when the ping isn't pinging or inheriting?

1
what do you mean by ` doesn't print (but does ping)` ? - Mritunjay
The ping process runs and pings localhost but the node program doesn't print to stdout. - dbenny
but I copied your code and it's working fine I think. - Mritunjay
Even with console.log. Basically I've narrowed it down - Node doesn't seem to get stdout until the process has finished in some cases - others it can get a live update. Not sure what the difference between these two are. - dbenny
It actually works fine in latest node version. Probably, you'd just better update yours! - blade091

1 Answers

0
votes

There have been lot of issue fixes as well as feature improvements with respect to console printing, on the lines of chunking and buffering. As the issue is no more reproducible, I would assume that this could be due to one of the under-documented behavior of the then Node, based on how many bytes of data is available for printing.

As this question is still open, I would request originator to see if you are satisfied with this explanation, or are looking for more concrete ones, which case I would need to reproduce this in the said version of node and debug further.