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

How to access variables declared in main app.js in separate route files in node.js Express 2.5.5?

How to access variables declared in main app.js in separate route files in node.js Express 2.5.5?

Problem

I just started using a new version of Express (2.5.5) that by default creates a ./routes directory along with ./views and ./public

Inside of routes there is a index.js file which contains:

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Express' })
};

by default (after running express from the commandline) and this is the routes section in the main app.js:

// Routes

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

I've set up a variable for a redis client in the main app.js:

var redis = require('redis'),
    db = redis.createClient();

and I was wondering how I could access the methods of db (and whatever other modules I require in app.js) in the files contained in ./routes

Problem courtesy of: nak

Solution

I really liked Jamund's solution, but I would extend the concept to this:

// db.js
var redis = require('redis');
module.exports = redis.createClient();

// index.js
var db = require(.'/db')

// whatever other file
var db = require(.'/db')
// do something with db
db.disconnect();

both db on index and other file would get the same instance of the redis client

Solution courtesy of: Marcel M.

Discussion

View additional discussion.



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

Share the post

How to access variables declared in main app.js in separate route files in node.js Express 2.5.5?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×