2012-10-17 42 views
57

在node.js中,我想找到一种方法来获取Unix终端命令的输出。有没有办法做到这一点?在node.js中获取shell命令的输出

function getCommandOutput(commandString){ 
    //now how can I implement this function? 
    //getCommandOutput("ls") should print the terminal output of the shell command "ls" 
} 
+0

这是一个重复的,或者它描述完全不同的东西? http://stackoverflow.com/questions/7183307/node-js-execute-command-synchronously-and-get-result –

+0

[This](http://davidwalsh.name/sync-exec)可能会让你感兴趣。 – benekastah

回答

80

多数民众赞成在我现在工作的项目中做到这一点。

var exec = require('child_process').exec; 
function execute(command, callback){ 
    exec(command, function(error, stdout, stderr){ callback(stdout); }); 
}; 

例子:获取git的用户

module.exports.getGitUser = function(callback){ 
    execute("git config --global user.name", function(name){ 
     execute("git config --global user.email", function(email){ 
      callback({ name: name.replace("\n", ""), email: email.replace("\n", "") }); 
     }); 
    }); 
}; 
+0

'上删除了'.exec'部分后就可以使用这个函数返回命令的输出了吗? (这就是我想要做的。) –

+1

多数民众赞成在代码做什么。看看编辑中的示例我刚刚制作了 – renatoargh

+2

@AndersonGreen您不希望该功能通过“返回”键盘正常返回,因为它正在异步运行shell命令。因此,最好传递一个回调代码,这个代码应该在shell命令完成时运行。 –

18

您正在寻找child_process

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

child = exec(command, 
    function (error, stdout, stderr) { 
     console.log('stdout: ' + stdout); 
     console.log('stderr: ' + stderr); 
     if (error !== null) { 
      console.log('exec error: ' + error); 
     } 
    }); 

正如指出的雷纳托,也有一些同步的exec包在那里现在也看到sync-exec这可能是更多的什么yo're寻找。请记住,node.js被设计成一个单线程高性能网络服务器,所以如果这就是你想要使用它的地方,那么远离sync-exec还有一些东西,除非你只在启动时使用它或者其他的东西。

+1

在这种情况下,我如何获得命令的输出?是包含命令行输出的“stdout”吗? –

+0

另外,是否有可能做类似的事情,而不使用回调? –

+0

正确,标准输出包含程序的输出。不,没有回调就无法做到。 node.js中的所有东西都是以非阻塞为导向的,这意味着每次执行IO时都将使用回调函数。 – hexist

相关问题