Javascript/Node.js: Problem Assigning Variable After Async Shell CMD

The Doctor

Senior Member
Joined
Dec 18, 2010
Messages
1,110
Reaction score
474
In Node I need to return the value of a shell command to a global but it doesn't work; however, the same command using console.log works fine. Why does my global always wind up as "undefined?"

Code:
function RunCMD(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) });
}


// If I do this, I don't get the variable assignment...
RunCMD( "uname", ["-v"], function(text) { global.CMDResp = text; });

// But if I do this I get the console.log output???
RunCMD( "uname", ["-v"], function(text) { console.log(text); });
 
This should get you going:

Code:
"use strict";

global.CMDResp = function RunCMD(input){...}
 
Back
Top