Last Updated: February 25, 2016
·
644
· coch

Referencing the main app module in sub modules

Doing something like this:

var app = require.main.exports;

At the start of your app's sub-modules gives you swift access to objects defined and exported in your app's main module (and the chance to easily define such objects in your modules) without having to explicitely pass around a pointer to the app. This is particularily useful, for instance, in Express (or likely frameworks) to do auto-routing inside controllers:

/* In app.js */
var app = module.exports = express.createServer();
// ...
require('./controllers');

/* In controllers.js */
var app = require.main.exports;
app.get(/* ... */);
// ...