Here is my basic node.js app with only two files:
app.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
module.exports = {
test: "test"
};
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// defining middlewares
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and my index.js:
var server = require('../app');
exports.index = function(req, res){
console.log(server);
res.send('Hello world');
};
My problem is when I go to http:\\localhost:3000 , I see in my console {} instead of {test: "test"} , it looks like the module.eports doesn't work correctly. Why ?
Requiring index.js from within app.js, and then requiring app.js from within index.js, looks like code smell to me. Additionally, if you use var app = module.exports = express() then Express is able to treat your app as middleware (so for instance, you could have a second app that requires the first app, and passes some requests to it.
When I need to access app inside another required file I do the following:
// ./routes/index.js
module.exports = function(app){
var routes = {};
routes.index = function(req, res){
console.log(app.myConfig);
res.send('Hello world');
};
return routes;
};
// ./app.js
var app = module.exports = express();
app.myConfig = {foo:'bar'};
var routes = require('./routes/index.js')(app);
You don't need to include app in index.js
indes.js should just be
exports.index = function(req, res){
console.log(server);
res.send('Hello world');
};
And I am assuming index.js is in the routes folder like so
app.js
routes
index.js