gs-rp gs-rp - 3 months ago 10
Node.js Question

export var to routes files expressjs

I'm completely new to nodejs + expressjs comming from php and I'm getting trouble how to export/include a var to my routes/users.js file.

on app.js I have:

//database connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});


... some code

var user = require('./routes/user');
//here I include my routes/files (I dont know if it's right to include the routes here - for learning purposes it works for now)

... more code until starts the server

On my /routes/user.js

app = require('../app');
//var mysql = require('mysql');
var baseUrl = app.get('baseUrl');

app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});


and I get the express error: 500 ReferenceError: connection is not defined

The connection works because if I move the content from users.js to app.js I can query the database.

My questions is how to inject the var connection to be used on routes/users.js

Any help / hint to understand this is very appreciated. Thanks in advance.

Answer

There are several ways you could do this. A couple solutions might be:

  1. Create a resources.js file that creates and exports the connection. Then require() resources.js in every source file where you need it.

  2. Pass the connection to your user route file. Something like this:

// app.js
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'dbNodeExpress'
});
require('./routes/user')(connection);


// routes/user.js
module.exports = function(connection) {
  app.get('/users_mysql', function(req, res){
    connection.query('SELECT * FROM users', function(err, users){
      res.json(users);
    });
  });
};