32
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 = ?

如何在 exec 函数之外找到用户名?

4

2 回答 2

34

您可以向 exec 函数传递回调。当 exec 函数确定用户名时,您使用用户名调用回调。

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


由于 JavaScript 的异步特性,你不能这样做:

    var username;

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

    child();

    console.log( username );

这是因为该行console.log( username );不会等到上面的函数完成。


回调说明:

    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.
于 2013-10-18T06:29:14.773 回答
4

您可以在具有回调的函数中编写“exec”语句......像这样

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);
});
于 2013-10-18T07:25:33.447 回答