NodeJS requiring modules


First off, I am a totally new developer with regards to Node.js.

I have started creating a sample express application, and I wanted to use an additional module to learn more about it. I have installed via npm the "mysql" module, all fine.

I have added it at the beginning of app.'s, like this:

var mysql = require('mysql');

now, as you already know, express created an index.js file inside the directory routes: i would like to be able to access the mysql variable to connect to the db from this index.js page but, using the command

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',

obviously doesn't work, giving the "500 ReferenceError: mysql is not defined".

Of course, I am sure I need to pass this variable, but I really have no clue, can any good soul enlighten me? I know this is a very small and basic thing, but I tried this already, and doesn't seem to work:

... app.get('/', routes.index, mysql); ...

and on index.js:

exports.index = function(req, res, mysql){ ...
Problem courtesy of: user1130217


In Node.js, you should require modules in the files you need to use them in; so, if you want to use the mysql package in your routes/index.js file, at the top of that file, do

var mysql = require('mysql');

You may end up requiring a module in more than one file; this is normal and, in many ways, a good thing (no namespacing issues, etc.)

If you want to learn more about modules and packages, you may be interested in these two screencasts:

Solution courtesy of: Michelle Tilley


Passing the mysql object through app.get() would be a normal reaction, but I'm pretty sure you're over-thinking it.

It's as simple as including var mysql = require('mysql'); at the top of routes/index.js. In fact, you may find that you don't even need to require mysql in app.js if all database interactions are done in your routes.

Discussion courtesy of: Travis

This recipe can be found in it's original form on Stack Over Flow.