问题
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 usingMySQL_poolas 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