nodejs: child_process.spawn not reporting exit code
Asked Answered
E

1

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
Exurbia answered 30/4, 2016 at 20:57 Comment(0)
M
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.

Mucus answered 30/4, 2016 at 21:1 Comment(1)
Awesome! Works as expected.Exurbia

© 2022 - 2024 — McMap. All rights reserved.