0

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?

1
  • 1
    My guess would be that mysqlConn.connect(); returns undefined. At least the return value is not used the the examples. You shuold be able to call query on mysqlConn instead Commented Mar 15, 2015 at 19:06

1 Answer 1

1

The problem is not with scoping, but an assumption that the call to connect returns a connection object. In the node module for mySql this is not the case, as it is on other platforms. The connect is a procedure not a function. IE it performs an operation, but returns no result. However, in JavaScript all functions do return something. In the case of no explicit return statement they return undefined. That means that in your code you explicitly assign undefined to connection. Change the code to the following and you should be good to go

var database = require('mysql');

(function (db) { 

    var mysqlConn = db.createConnection ({...});
    mysqlConn.connect();

    var function moduleFunction (someArgs) {
        mysqlConn.query('SELECT * FROM ....', function (err, result) {...});
    }

}(database);

Whether that approach is prudent from a connection pooling perspective is not so obvious. So it might be worth investigating from the intended use of your module

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.