Dail
Dail

Reputation: 4606

How to share the same variable between modules?

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

Upvotes: 7

Views: 2884

Answers (1)

alessioalex
alessioalex

Reputation: 63653

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
}

Upvotes: 11

Related Questions