Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  196] [ 6]  / answers: 1 / hits: 72755  / 11 Years ago, fri, october 18, 2013, 12:00:00
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('rn','');
}
);

var username = ?


How can I find username outside from exec function ?


More From » node.js

 Answers
3

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('rn','');
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('rn','');
});

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.

[#74907] Thursday, October 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dayanaracolleeng

Total Points: 7
Total Questions: 96
Total Answers: 104

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
;