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 0Request 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?
The stderr event will not be emitted when the ping command is not able to reach the target host. This is because stderr is used to output error messages, and there is no error in this case. Instead, the stdout event will be emitted with information about the timeout of the ping request.
To handle both cases, you can listen for the stdout event and check the output for error messages:
ping.stdout.on('data', function(data){ if (data.toString().indexOf("Request timeout") >= 0) { // Handle error } else { // Handle success util.print(data); } });