Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 503
Dail Avatar asked Dec 19 '11 09:12

Dail


People also ask

What does global () do in Python?

Python – globals() function globals() function in Python returns the dictionary of current global symbol table. Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.

What is __ all __ in Python?

PACKAGES. In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.

Can you import a variable from another Python file?

How do I import a variable from one file to another in Python? import <file_name> and then use <file_name>. <variable_name> to access variable. from <file_name> import <variable_names> and use variables.


1 Answers

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
}
like image 87
alessioalex Avatar answered Sep 28 '22 05:09

alessioalex