Sunday, 4 June 2017

Node JS: variable usage between modules

I have two modules to represent my problem/confusion:

f2.js:

var user;

var getName = function(userName) {
    user = userName;
    return user;
};

module.exports.getName = getName;
module.exports.user = user;

f1.js:

var userName = require('./f2.js');
console.log(userName.getName("myName"));

// I need below to return "myName" too - how?
console.log(userName.user);

When I run f1.js, I get these:

myName
undefined

What am I missing in terms of scoping or perhaps asynchronous coding? Logically, I know getName function will always run in front so how can I read 'user' variable in other modules as set with that pre-run function? I eventually want to expand this with express and use it as site login



via Ben77

No comments:

Post a Comment