Estus Flask
Estus Flask

Reputation: 222379

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?

Upvotes: 11

Views: 3238

Answers (2)

Maciej Kravchyk
Maciej Kravchyk

Reputation: 16607

Additionally if you want to see the error message:

if (childProcess.stderr !== null) {
  childProcess.stderr.on('data', (data) => {
    console.log(data);
  });
}

Upvotes: 2

robertklep
robertklep

Reputation: 203251

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');
  }
});

Upvotes: 16

Related Questions