Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we access variable from callback function in node.js?

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 ?

like image 433
Devang Bhagdev Avatar asked Oct 18 '13 06:10

Devang Bhagdev


People also ask

How do you pass a callback function in node?

var myCallback = function(data) { console. log('got data: '+data); }; var usingItNow = function(callback) { callback('get it? '); }; Now open node or browser console and paste the above definitions.

Can callbacks have parameters?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

How do you read a callback function?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

How do you call a function inside a callback?

You need to use the . call() or . apply() methods on the callback to specify the context which the method is called upon. The callback method remote_submit does not know what this will be anymore and thus when it calls the callback methods they're executed like normal functions not on an object.


1 Answers

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. 
like image 193
Matthias Holdorf Avatar answered Sep 19 '22 21:09

Matthias Holdorf