1

I have an ExpressJS 3 app and have my routes in a separate file. I'd like to declare some configs in my app.js that are available in the routes file - outside of the route definitions themselves.

In my app.js I would like to do something such as:

app.set('path_to_models', '/path/models/');

Then in my routes/index.js file I would like to be able to do this:

var Product = require(app.get('path_to_models') + 'product');

exports.list = function(req, res){
  return Product.find(function (err, products) {
    if (!err) {
       res.render('product/manage', { products: products });
    } else {
       res.render('5xx');
    }
  });
};

I've seen a few posts related to this but none really addressed what I am looking for. I know that I can wrap the routes in a function but would like an alternative way that will keep my code as is if at all possible.

Cœur
  • 37,241
  • 25
  • 195
  • 267
cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • I just saw the last post on http://stackoverflow.com/questions/10090414/express-how-to-pass-app-instance-to-routes-from-a-different-file which recommends declaring ap as a global. Are there any drawbacks to doing this? because that works for me. – cyberwombat Aug 19 '12 at 22:38
  • replace your 'app.get' with 'app.set' and it should work – matz3 Aug 20 '12 at 06:09

2 Answers2

2

I just make a separate config module that holds my configuration and in any module that needs info from the config, I just require it as normal. Why drag express into the mix when a more loosely coupled approach works just fine.

config.js

exports.pathToModels = "/path/to/models";

routes.js

var config = require("./config");
console.log(config.pathToModels);
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
1

Simply pass app as an argument to `routes/index.js':

var routes = require('./routes/index.js')(app);

UPDATED: This should be

var routes = require('./routes/index.js').init(app);

and in routes/index.js:

var app;
exports=function(whichApp) {

UPDATED: This should be

exports.init=function(whichApp) {

  app=whichApp;
  // do initialization stuff
  return exports;
}

exports.list=...
ebohlman
  • 14,795
  • 5
  • 33
  • 35
  • Change the initial `require` to `require('./routes/index.js').init(app);` and the second line of `index.js` to `exports.init=function(...)`. – ebohlman Aug 21 '12 at 05:00