[翻译]  Execute bash command in Node.js and get exit code

[CHINESE]  在Node.js中执行bash命令并获取退出代码


I can run a bash command in node.js like so:

我可以在node.js中运行bash命令,如下所示:

var sys = require('sys')
var exec = require('child_process').exec;

function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", function(err, stdout, stderr) {
  console.log(stdout);
});

How do I get the exit code of that command (ls -la in this example)? I've tried running

如何获取该命令的退出代码(在此示例中为ls -la)?我试过跑步

exec("ls -la", function(err, stdout, stderr) {
  exec("echo $?", function(err, stdout, stderr) {
    console.log(stdout);
  });
});

This somehow always returns 0 regardless of the the exit code of the previous command though. What am I missing?

不管以前命令的退出代码如何,这总是返回0。我错过了什么?

3 个解决方案

#1


16  

Those 2 commands are running in separate shells.

这两个命令在单独的shell中运行。

To get the code, you should be able to check err.code in your callback.

要获取代码,您应该能够在回调中检查err.code。

If that doesn't work, you need to add an exit event handler

如果这不起作用,则需要添加退出事件处理程序

e.g.

例如

dir = exec("ls -la", function(err, stdout, stderr) {
  if (err) {
    // should have err.code here?  
  }
  console.log(stdout);
});

dir.on('exit', function (code) {
  // exit code is code
});

#2


3  

From the docs:

来自文档:

If a callback function is provided, it is called with the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.

如果提供了回调函数,则使用参数(error,stdout,stderr)调用它。成功时,错误将为空。出错时,错误将是错误的实例。 error.code属性将是子进程的退出代码,而error.signal将设置为终止进程的信号。除0以外的任何退出代码都被视为错误。

So:

所以:

exec('...', function(error, stdout, stderr) {
  if (error) {
    console.log(error.code);
  }
});

Should work.

应该管用。

#3


1  

In node documentation i found this information for the callback function:

在节点文档中,我找到了回调函数的这些信息:

On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.

成功时,错误将为空。出错时,错误将是错误的实例。 error.code属性将是子进程的退出代码,而error.signal将设置为终止进程的信号。除0以外的任何退出代码都被视为错误。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号