在node.js中,我想找到一种获取Unix终端命令输出的方法。有没有办法做到这一点?
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", "") });
});
});
};
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指出的那样,现在也有一些同步的exec包,请参阅sync-exec,这可能更像是你在寻找什么。请记住,node.js设计为单线程高性能网络服务器,所以如果你想要使用它,请远离sync-exec类似的东西,除非你只是在启动时使用它或者其他的东西。
如果您使用的是晚于7.6的节点并且您不喜欢回调样式,那么您还可以使用node-util的promisify
函数和async / await
来获取干净地读取的shell命令。以下是使用此技术的已接受答案的示例:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
module.exports.getGitUser = async function getGitUser () {
const name = await exec('git config --global user.name')
const email = await exec('git config --global user.email')
return { name, email }
};
这还有一个额外的好处,即在失败的命令上返回被拒绝的承诺,可以使用异步代码中的try / catch
来处理。
感谢Renato的回答,我创建了一个非常基本的例子:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
它只会打印你的全局git用户名:)