1

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!!

Buruk
  • 49
  • 5
  • Did you try to console.log `usersController` ? – Zagonine Apr 11 '19 at 13:20
  • 1
    Honestly, instead of doing that, I would recommend using TypeScript (if possible). That way, you can use the language to pass data around files, rather these (oftentimes helpful) module export libraries. https://github.com/Microsoft/TypeScript-Node-Starter/tree/master/src/controllers – jburtondev Apr 11 '19 at 13:40
  • You would try https://nodejs.org/api/modules.html – Abdulrahman Falyoun Apr 11 '19 at 13:50
  • file is named `usersConroller.js` (or just a typo here)?, and you load `./usersCon`**t**`roller` – Metux Apr 11 '19 at 13:53

1 Answers1

1

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;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
prashantpiyush
  • 197
  • 2
  • 8