I'm writing a multi-file node.js application, and I'm using modules to organize it's functionality like so:
var custom_module = require('./module');
It has a lot of dependencies, namely MySQL. I don't want to pass the connection object as an argument to all the functions in the module (since all of them require it), so I tried something like this:
// Module
var database = require('mysql');
(function (db) {
var mysqlConn = db.createConnection ({...});
var connection = mysqlConn.connect();
var function moduleFunction (someArgs) {
connection.query('SELECT * FROM ....', function (err, result) {...});
}
}(database);
I get the error cannot call query method of undefined, basically the object hasn't been initialized / out of scope.
It is noteworthy that the module had time to load before the function is called since moduleFunction is called as a result of
express.get('/url_here', function (req, res) {
custom_module.moduleFunction(....);
});
in the main script.
Is there any way to make sure the connection object is initialized and in scope at the time any module functions are called? Or do I have to initialize it every time and pass it as an argument in the callback?
mysqlConn.connect();returns undefined. At least the return value is not used the the examples. You shuold be able to callqueryonmysqlConninstead