Node child process event listen
This works for me:
var child_process = require('child_process');var cmd = 'ls';var value = ['-z', '/usr'];var opt = { };var child = child_process.spawn(cmd, value, opt);child.stdout.on('data', function (data) { console.log("IM HERE"); console.log('data' + data);});child.stderr.on('data', function (data) { console.log("IM HERE - Error"); console.log('test: ' + data);});child.on('close', function (code) { console.log("IM HERE"); console.log("close");});
Console output:
/*IM HERE - Errortest: ls: invalid option -- 'z'Try 'ls --help' for more information.IM HEREclose*/
The issue in your side, maybe the command you're spawning doesn't use stderr?
Update
If I add process.exit()
var child_process = require('child_process');var cmd = 'ls';var value = ['-z', '/usr'];var opt = { };var child = child_process.spawn(cmd, value, opt);child.stdout.on('data', function (data) { console.log("IM HERE"); console.log('data' + data);});child.stderr.on('data', function (data) { console.log("IM HERE - Error"); console.log('test: ' + data); process.exit(1); // <<<< this works as expected and exit the process asap});child.on('close', function (code) { console.log("IM HERE"); console.log("close");});
The ouput is slightly different (no close event from the child)
/*IM HERE - Errortest: ls: invalid option -- 'z'Try 'ls --help' for more information.*/
You can "play" with the code here: https://tonicdev.com/shanshan/cp-spawn-piping
You can subscribe to the data
event(stdout or stderr) and listen it
child.stdout.on('data', function (buf) { console.log(buf.toString());});
For example
const spawn = require('child_process').spawn;const child = spawn('ping', ['google.com']);child.stdout.on('data', function (buf) { console.log('buf receive'); console.log(buf.toString());});