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

新手上路,请多包涵

在 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"
}

原文由 Anderson Green 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

这是我在我目前正在从事的项目中使用的方法。

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

原文由 Renato Gama 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您使用的节点高于 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 () {
  // 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 处理。

原文由 Ansikt 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题