问题
I'm trying to capture the stdout from a spawn
ed 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:
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.
来源:https://stackoverflow.com/questions/24632914/node-js-child-process-spawn-no-stdout-unless-inherit