Shell command execution in nodejs

NodeJS, Web Development, 2016-03-19 23:34:26 UTC

Sometimes, we need a function that doesn't exist in nodejs. Or sometimes we know other function better to do 'this' job rather than in nodejs function. So, for this we need to execute some command via shell command. And for me, here is how to run shell command;

function run_cmd(cmd, args, callBack ) {
    var spawn = require('child_process').spawn;
    var child = spawn(cmd, args);
    var resp = "";

    child.stdout.on('data', function (buffer) { resp += buffer.toString() });
    child.stdout.on('end', function() { callBack (resp) });
} // ()

// You can use: run_cmd( "ls", ["-l"], function(text) { console.log (text) }); run_cmd( "hostname", [], function(text) { console.log (text) });