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

4
  • Did you try to console.log usersController ? Commented Apr 11, 2019 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. github.com/Microsoft/TypeScript-Node-Starter/tree/master/src/… Commented Apr 11, 2019 at 13:40
  • You would try nodejs.org/api/modules.html Commented Apr 11, 2019 at 13:50
  • file is named usersConroller.js (or just a typo here)?, and you load ./usersCon**t**roller Commented Apr 11, 2019 at 13:53

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.