Alex Morgan Alex Morgan - 5 months ago 8
Node.js Question

Accessing the data set in a function of a globally define variable in another function

I'm still a bit of a noob at JS and thus I have the following question. I have this JS:

var twoFactorAuthCode;

fs.readFile('file.2fa', function (err, data) {
if (err) {
logger.warn('Error reading neyotbot1.2fa. If this is the first run, this is expected behavior: '+err);
} else {
logger.debug("Found two factor authentication file. Attempting to parse data.");
twoFactorAuth = JSON.parse(data);
SteamTotp.getTimeOffset(function (error, offset, latency) {
if (error) {
logger.warn('Error retrieving the time offset from Steam servers: ' + error);
} else {
timeOffset = offset + latency;
}
});
console.log(twoFactorAuthCode); //returns undefined
twoFactorAuthCode = SteamTotp.getAuthCode(twoFactorAuth.shared_secret, timeOffset);
console.log(twoFactorAuthCode); //returns what is expected
}
console.log(twoFactorAuthCode); //also returns what is expected
});

client.logOn({
accountName: config.username,
password: config.password,
twoFactorCode: twoFactorAuthCode //this is still set as undefined
});


My problem is that although the variable twoFactorAuthCode has a global scope, when it's assigned a value in the fs.readFile() function, it does not carry the data over to the next function client.logOn().

My question is, is it possible to get the data from the first function over to the second function using the variable.
I couldn't find anything simple enough to help me with this.

z0r z0r
Answer

The problem is that your arguments to client.logOn are initialised before your other function is called. Put that call inside another function and call it after the other one.

function myLogOn() {
  client.logOn({
    accountName:    config.username,
    password:       config.password,
    twoFactorCode:  twoFactorAuthCode
  });
};
myLogOn();

If fs.readFile is asynchronous, you may even need to move the call to logOn to be inside the callback function.

Comments