如何在模块之间共享相同的变量? [英] How to share the same variable between modules?

查看:74
本文介绍了如何在模块之间共享相同的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Node.JS与Express.js一起使用,我需要在模块之间共享一个变量,我必须这样做,因为该变量是mysql连接池,该池在Node的开头创建了3个Mysql连接.js,然后我希望其他模块将使用这些连接,而无需重新创建其他池.

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.

这可能吗?

谢谢

推荐答案

有2个选项:

  • 将该变量设为全局变量,例如:global.MySQL_pool = ....这样,您可以使用MySQL_pool作为变量来在任何地方访问它.
  • 将它传递给每个需要它作为功能参数的模块,例如:

  • 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);

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

其中db.js是:

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

这篇关于如何在模块之间共享相同的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆