Search code examples
node.jsshellcommand-line-interface

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


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

Solution

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

    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("\n", ""), email: email.replace("\n", "") });
            });
        });
    };