Anderson Green Anderson Green - 1 year ago 147
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 Source

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", function(name){
        execute("git config --global", function(email){
            callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download