Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

ExpressJS and passing variables between separate route files

ExpressJS and passing variables between separate route files

Problem

I'm using ExpressJs with Node.js and have put all my routes into a 'routes' folder.

On the server, I do my DB connection, then define my routes, like this:

var routes = require('./routes');

var db;
dbconnect = new mongo.Db(config.mongo_database, new mongo.Server(config.mongo_host, config.mongo_port, {}), {});
dbconnect.open(function (err, db) {

  db.authenticate(config.mongo_user, config.mongo_pass, function (err, success) {
    if (success) {

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

      //routes/users.js
      app.get('/users', routes.users);

    }
  });
});

I want to access the 'db' object inside each of these routes javascript files. How would I pass that from this 'app.js' file to the index.js or users.js?

Thank you!

Problem courtesy of: dzm

Solution

One suggestion is to expose your routes via a function which accepts a db parameter:

routes.js:

module.exports = function(db) {
    return {
        index: function(req, res, next) {
            // Funky db get stuff
        }
    }
}

Wrapping values in a closure like this and returning an object with more functions is a useful pattern, sometimes called "Revealing Module Pattern". It shows the dependencies clearly, allowing for easy testing (using e.g. a mock db object) while still using a flexible functional approach.

Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

ExpressJS and passing variables between separate route files

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×