Here is an example where child process error
is not fired:
const spawn = require('child_process').spawn;
const childProcess = spawn('tar', ['--wrong-option'], { stdio: 'inherit' });
childProcess.on('error', err => {
console.error('err: ', err);
});
Why is it so? How can the error (error code in particular) be caught from spawned process?
error
events are only generated when spawning the child itself is causing a problem; for instance, when the executable doesn't exist.
To catch errors "thrown" by the child process, you should listen for exit
events and check the code
and signal
arguments:
childProcess.on('exit', (code, signal) => {
if (code) {
console.error('Child exited with code', code)
} else if (signal) {
console.error('Child was killed with signal', signal);
} else {
console.log('Child exited okay');
}
});
Additionally if you want to see the error message:
if (childProcess.stderr !== null) {
childProcess.stderr.on('data', (data) => {
console.log(data);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With