Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching errors from spawned Node.js process

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?

like image 777
Estus Flask Avatar asked Jun 29 '17 18:06

Estus Flask


2 Answers

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');
  }
});
like image 73
robertklep Avatar answered Nov 18 '22 18:11

robertklep


Additionally if you want to see the error message:

if (childProcess.stderr !== null) {
  childProcess.stderr.on('data', (data) => {
    console.log(data);
  });
}
like image 26
Maciej Krawczyk Avatar answered Nov 18 '22 17:11

Maciej Krawczyk