在 node.js 中执行并获取 shell 命令的输出 [英] Execute and get the output of a shell command in node.js
本文介绍了在 node.js 中执行并获取 shell 命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 node.js 中,我想找到一种方法来获取 Unix 终端命令的输出.有没有办法做到这一点?
In a node.js, I'd like to find a way to obtain the output of a Unix terminal command. Is there any way to do this?
function getCommandOutput(commandString){
// now how can I implement this function?
// getCommandOutput("ls") should print the terminal output of the shell command "ls"
}
推荐答案
这是我在我目前正在进行的项目中使用的方法.
This is the method I'm using in a project I am currently working on.
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
};
检索 git 用户的示例:
Example of retrieving a git user:
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("
", ""), email: email.replace("
", "") });
});
});
};
这篇关于在 node.js 中执行并获取 shell 命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文