在Node.js中执行bash命令并获取退出代码 [英] Execute bash command in Node.js and get exit code

查看:209
本文介绍了在Node.js中执行bash命令并获取退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以像这样在node.js中运行bash命令:

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

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

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

无论上一个命令的退出代码如何,它总是以某种方式返回0.我想念什么?

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

推荐答案

这2条命令在单独的shell中运行.

Those 2 commands are running in separate shells.

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

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

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

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

例如

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

这篇关于在Node.js中执行bash命令并获取退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆