Anderson Green Anderson Green - 2 months ago 13
Node.js Question

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

Answer

Thats the way I do it in a project I am working now.

var exec = require('child_process').exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
};

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