简体   繁体   English

nodejs:child_process.spawn不报告退出代码

[英]nodejs: child_process.spawn not reporting exit code

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 . 在为一个简单的工具编写单元测试时,我无法获得以require('child_process').spawn开始的子进程的进程退出代码require('child_process').spawn To simplify if down, consider this simple node command which exits with code 35: 要简化if down,请考虑使用代码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 . 现在考虑以下文件,其中上面的命令是用execspawn执行的。 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 obvious at 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: spawn()的第二个参数中删除双引号, spawn()将自动确保参数不会因空格等而意外分离:

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);" 否则节点将传递的(js)代码字面上视为"process.exit(35);" (a string literal) which is basically a no-op and so it exits with code 0. (一个字符串文字),它基本上是一个无操作,所以它以代码0退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM