Execute bash command in Node.js and get exit code

ぃ、小莉子 提交于 2019-11-28 17:05:12

问题


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

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

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?


回答1:


Those 2 commands are running in separate shells.

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

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:


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.

So:

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

Should work.




回答3:


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.



来源:https://stackoverflow.com/questions/37732331/execute-bash-command-in-node-js-and-get-exit-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!