Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: how to pass variables to mounted middleware

I've just started to play around with Expressjs and I'm wondering how to pass variables to mounted middleware/sub application. In the following example, I'd like the config object passed to my /blog/index

in app.js

var express = require('express');
var app = express();
//...
var config = {}
//...
app.use('/blog', require('./blog/index')

in /blog/index.js

var express = require('express');
app = module.exports = express();

app.use(express.static(...
app.get('/', function(req, res, next) {
  //handle the req and res
}

Thanks,

like image 701
Ludohen Avatar asked Jan 30 '13 04:01

Ludohen


1 Answers

I see two options here:

  1. Since your blog app is an express application, you can use app.set and app.get. E.g.

     blog = require('./blog/index');
     blog.set('var1', value1);
     blog.set('var2', value2); 
     ...
     app.use('/blog', blog);
    

    And in blog/index.js use app.get('var1') to get the value of var1.

  2. You can wrap the blog express application in another function that accepts configuration parameters (much like the static middleware accepts a directory name) and returns the configured application. Let me know if you want an example.

EDIT: Example for the 2nd option

app.js would look like this:

var blog = require('./blog/index');
...
var config = {};
app.use('/blog', blog(config));

and /blog/index.js like that:

var express = require('express')

module.exports = function(config) {
    var app = express();
    // configure the app and do some other stuffs here
    // ...

    return app;
}
like image 51
nimrodm Avatar answered Oct 27 '22 08:10

nimrodm