在node.js中获取shell命令的输出

在node.js中,我想find一种方法来获得Unixterminal命令的输出。 有没有办法做到这一点?

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

那就是我现在在做的一个项目中的做法。

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

你正在寻找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); } }); 

正如Renato所指出的那样,现在也有一些同步执行包,请参阅sync-exec ,这可能更适合您寻找的内容。 请记住,node.js被devise成一个单线程的高性能networking服务器,所以如果这就是你想要使用它,远离sync-exec有点东西,除非你只在启动时使用它或者其他的东西。