如何在Node.js中共享变量?

时间:2019-04-11 13:18:05

标签: node.js

我想在节点中的不同文件之间共享变量。 我见过很多网站,但没有一个对我有用。

其中一些网站

Share variables between files in Node.js?

https://stackabuse.com/how-to-use-module-exports-in-node-js/

usersConroller.js文件

module.exports.fetchedUser = fetchedUser;
module.exports.fetchedUser.branchId = branchId;
module.exports.fetchedUser.role = role;
module.exports.isLoggedIn = isLoggedIn;

然后在另一个文件上 我导入了userController并尝试访问变量 这样

let usersController = require('./usersController');
let fetchedUser = usersController.fetchedUser;
let branchId = usersController.branchId;
let role = usersController.role;
let isLoggedIn = usersController.isLoggedIn;

并且当我console.log()个变量时,表示undefined 任何帮助。 谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果任何地方都没有错字,并且您在require语句中使用了正确的文件名,那么问题就出在您访问变量的方式上。

您的导出变量看起来像这样

exports = {
    fetchedUser: {
        branchId: <some_value>,
        role: <some_other_value>
    },
    isLoggedIn: <another_value>
}

现在,让我们看一下您的代码:

// 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 acctually 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;