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

Anderson Green picture Anderson Green · Oct 17, 2012 · Viewed 120.8k times · Source

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

Answer

Renato Gama picture Renato Gama · Oct 17, 2012

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