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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37732331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:17:46  来源:igfitidea点击:

Execute bash command in Node.js and get exit code

node.jsbashexit-code

提问by Marc Bacvanski

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 -lain 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。我错过了什么?

回答by Joe

Those 2 commands are running in separate shells.

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

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

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

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

如果这不起作用,您需要添加一个exit事件处理程序

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
});

回答by andlrc

From the docs:

从文档:

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

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

So:

所以:

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

Should work.

应该管用。

回答by Borja Tur

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 processwhile 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 将是 Error 的一个实例。error.code 属性将是子进程的退出代码,而 error.signal 将被设置为终止进程的信号。除 0 以外的任何退出代码都被视为错误。