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

Execute bash command in Node.js and get exit code

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

1
2
3
4
5
6
7
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);
});

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

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

尽管如此,无论上一个命令的退出代码如何,它总是返回0。 我想念什么?


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

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

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

例如

1
2
3
4
5
6
7
8
9
10
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
});


从文档:

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.

所以:

1
2
3
4
5
exec('...', function(error, stdout, stderr) {
  if (error) {
    console.log(error.code);
  }
});

应该管用。


child_process.spawnSync()

此函数公开了最好的同步接口:https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env node

const child_process = require('child_process');
let out;

out = child_process.spawnSync('true');
console.log('status: ' + out.status);
console.log('stdout: ' + out.stdout.toString('utf8'));
console.log('stderr: ' + out.stderr.toString('utf8'));
console.log();

out = child_process.spawnSync('false');
console.log('status: ' + out.status);
console.log('stdout: ' + out.stdout.toString('utf8'));
console.log('stderr: ' + out.stderr.toString('utf8'));
console.log();

out = child_process.spawnSync('echo', ['abc']);
console.log('status: ' + out.status);
console.log('stdout: ' + out.stdout.toString('utf8'));
console.log('stderr: ' + out.stderr.toString('utf8'));
console.log();

输出:

1
2
3
4
5
6
7
8
9
10
11
12
status: 0
stdout:
stderr:

status: 1
stdout:
stderr:

status: 0
stdout: abc

stderr:

在Ubuntu 19.10的Node.js v10.15.1中进行了测试。


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

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