How to share the same variable between modules?

核能气质少年 提交于 2020-01-12 07:46:09

问题


I'm using Node.JS with Express.js and I need to share a variable between modules, I have to do that because this variable is a pool of mysql connections, This pool creates 3 Mysql connections at the start of Node.js and then I would like that the other modules will use those connections without recreate other pools.

Is this possible?

Thanks


回答1:


There are 2 options:

  • make that variable a global one, for ex: global.MySQL_pool = .... This way you can access it everywhere by using MySQL_pool as the variable.
  • pass it for each module where you need it as a function param, for ex:

    var MySQL_pool = ... var my_db_module = require('./db')(MySQL_pool);

where db.js is:

module.exports = function (pool) {
  // access the MySQL pool using the pool param here
}


来源:https://stackoverflow.com/questions/8559043/how-to-share-the-same-variable-between-modules

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!