33
var sys = require('sys');
var exec = require('child_process').exec;
var cmd = 'whoami';
var child = exec( cmd,
      function (error, stdout, stderr) 
      {
        var username=stdout.replace('\r\n','');
      }
);

var username = ?

How can I find username outside from exec function ?

Devang Bhagdev
  • 633
  • 2
  • 8
  • 14
  • You can have the username outside of the exec function (ie in global or child scope) or you can have an object keep track of some scope variables – megawac Oct 18 '13 at 06:18
  • Is exec method asynchronous? – karaxuna Oct 18 '13 at 06:18
  • possible duplicate of [Pass additional parameter to Javascript callback function](http://stackoverflow.com/questions/11371673/pass-additional-parameter-to-javascript-callback-function) – ThorSummoner Jan 24 '15 at 00:07

2 Answers2

34

You can pass the exec function a callback. When the exec function determines the username, you invoke the callback with the username.

    var child = exec(cmd, function(error, stdout, stderr, callback) {
        var username = stdout.replace('\r\n','');
        callback( username );
    });


Due to the asynchronous nature of JavaScript, you can't do something like this:

    var username;

    var child = exec(cmd, function(error, stdout, stderr, callback) {
        username = stdout.replace('\r\n','');
    });

    child();

    console.log( username );

This is because the line console.log( username ); won't wait until the function above finished.


Explanation of callbacks:

    var getUserName = function( callback ) {            
        // get the username somehow
        var username = "Foo";    
        callback( username );
    };

    var saveUserInDatabase = function( username ) {
        console.log("User: " + username + " is saved successfully.")
    };

    getUserName( saveUserInDatabase ); // User: Foo is saved successfully.
Matthias Holdorf
  • 1,040
  • 1
  • 14
  • 19
  • ` callback(username); ^ TypeError: undefined is not a function at D:\wamp\www\keywords\ddd.js:7:5 at ChildProcess.exithandler (child_process.js:630:7) at ChildProcess.EventEmitter.emit (events.js:98:17) at maybeClose (child_process.js:730:16) at Socket. (child_process.js:943:11) at Socket.EventEmitter.emit (events.js:95:17) at Pipe.close (net.js:451:12)` – Devang Bhagdev Oct 18 '13 at 06:33
  • You have to define a function to pass as a callback. – Matthias Holdorf Oct 18 '13 at 06:38
  • with you first 4 lined code I am getting "undefiend is not a function" at 3rd line "callback(username)" – Devang Bhagdev Oct 18 '13 at 06:39
  • How can we define a function "child" as per 2nd commnet? – Devang Bhagdev Oct 18 '13 at 06:42
  • For people new to this, the first code block is really confusing without the wrapper that passes the callback function. Also, it seems the callback from exec receives three strings: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback – kilgoretrout Mar 12 '19 at 16:44
4

You can write the "exec" statement in a function that has a callback... Like This

var sys = require('sys');
var exec = require('child_process').exec;
var cmd = 'whoami';
function execChild(callback){
    var child = exec( cmd,
          function (error, stdout, stderr) 
          {
            username=stdout.replace('\r\n','');
             callback(username);
          }
 )};
    execChild(function(username){
    console.log(username);
});
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140