7

While writting unit tests for a simple tool, I was unable to get the process exit code of a child process started with require('child_process').spawn. To simplify if down, consider this simple node command which exits with code 35:

SHELL> node -e "process.exit(35)" &
[1] 23427
[1]+  Saída 35               node -e "process.exit(35)"

Now consider the following file, where the command above is executed with exec and with spawn. The target is catching the exit code:

SHELL> cat WTF.js 
var cp = require('child_process');

cp.exec('node -e "process.exit(35);"', function(err){
  console.log('child exit code (exec)', err.code);
});

cp.spawn('node', ['-e', '"process.exit(35);"']).on('exit', function(code){
  console.log('child exit code (spawn)', code);
});

But when it's run... surprise:

SHELL> node WTF.js
child exit code (exec) 35
child exit code (spawn) 0

Am I missing something about the spawn call?

SHELL> node --version 
v6.0.0

1 Answer 1

11

Remove the double quotes from the second parameter for spawn(), the spawn() will automatically take care of making sure the parameter is not accidentally separated due to spaces, etc:

cp.spawn('node', ['-e', 'process.exit(35);'])
  .on('exit', function(code){
    console.log('child exit code (spawn)', code);
  });

Otherwise node treats the passed (js) code literally as "process.exit(35);" (a string literal) which is basically a no-op and so it exits with code 0.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Works as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.