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
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.
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