I want to share variables between different files in node. I have seen many sites but none of them worked for me.
these are some of the sites
Share variables between files in Node.js?
https://stackabuse.com/how-to-use-module-exports-in-node-js/
usersConroller.js file
module.exports.fetchedUser = fetchedUser;
module.exports.fetchedUser.branchId = branchId;
module.exports.fetchedUser.role = role;
module.exports.isLoggedIn = isLoggedIn;
then on another file I imported userController and tried to access the variables as this
let usersController = require('./usersController');
let fetchedUser = usersController.fetchedUser;
let branchId = usersController.branchId;
let role = usersController.role;
let isLoggedIn = usersController.isLoggedIn;
and when i console.log()
the variables, is says undefined
any help.please?? Thank You for your help!!
If there is no typo anywhere and you are using correct file name in your require statement, then the problem is your way of accessing the variables.
Your export variable looks something like this
exports = {
fetchedUser: {
branchId: <some_value>,
role: <some_other_value>
},
isLoggedIn: <another_value>
}
Now, let's look at your code:
// this line should give you the desired result
let fetchedUser = usersController.fetchedUser;
// this a wrong way to access branchId
// let branchId = usersController.branchId;
// branchId is actually a property of fetchedUser
// so you'll have to first access that
let branchId = usersController.fetchedUser.branchId;
// alternatively (because fetchedUser is already
// saved in a variable):
branchId = fetchedUser.branchId;
// similar problem while accessing role property
// let role = usersController.role;
// correct way:
let role = fetchedUser.role;
// this line is correct
let isLoggedIn = usersController.isLoggedIn;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.