1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

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

Discussion in 'HTML & JavaScript' started by The Doctor, Jul 12, 2016.

  1. The Doctor

    The Doctor Jr. VIP Jr. VIP

    Joined:
    Dec 18, 2010
    Messages:
    971
    Likes Received:
    296
    Occupation:
    Computer Scientist, Engineer, Programmer.
    Location:
    ☆☆☆☆☆☆
    Home Page:
    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); });
     
  2. MrBlue

    MrBlue Senior Member

    Joined:
    Dec 18, 2009
    Messages:
    974
    Likes Received:
    680
    Occupation:
    Web/Bot Developer
    This should get you going:

    Code:
    "use strict";
    
    global.CMDResp = function RunCMD(input){...}