在终端中,我想找到一种方法来获得Unix node.js命令的输出。有没有办法做到这一点?
function getCommandOutput(commandString){
// now how can I implement this function?
// getCommandOutput("ls") should print the terminal output of the shell command "ls"
}
发布于 2012-10-18 02:47:33
这是我目前正在进行的一个项目中使用的方法。
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", "") });
});
});
};
发布于 2018-05-15 00:31:00
如果你使用的是node 7.6以后的版本,并且你不喜欢回调风格,你也可以使用node-util的promisify
函数和async / await
来获得清晰可读的外壳命令。下面是一个被接受的答案的例子,使用这种技术:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
module.exports.getGitUser = async function getGitUser () {
// Exec output contains both stderr and stdout outputs
const nameOutput = await exec('git config --global user.name')
const emailOutput = await exec('git config --global user.email')
return {
name: nameOutput.stdout.trim(),
email: emailOutput.stdout.trim()
}
};
这还有一个额外的好处,那就是在失败的命令上返回拒绝的承诺,这可以在异步代码中使用try / catch
处理。
发布于 2018-07-17 21:15:42
感谢Renato answer,我创建了一个非常基本的示例:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
它将只打印您的全局git用户名:)
https://stackoverflow.com/questions/12941083
复制相似问题