Execute and get the output of a shell command in node.js

前端 未结 5 615
无人及你
无人及你 2020-11-27 10:56

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){         


        
5条回答
  •  悲&欢浪女
    2020-11-27 11:25

    If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's promisify function with async / await to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:

    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 }
    };
    

    This also has the added benefit of returning a rejected promise on failed commands, which can be handled with try / catch inside the async code.

提交回复
热议问题