I'm writing a mudule express-based NodeJS app. Here are important parts of my app.js:
var express = require('express')
, routes = require('./routes')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var app = module.exports = express.createServer();
var ab = 'this is a test!';
// Configuration
app.configure(function(){
...
// Routes
app.get('/', routes.index);
app.listen(3000);
Routes.index - is a controller, that executes when '/' is requested. Here is the code:
exports.index = function(req, res){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
...
res.render('index.ejs', {
title: ab
})
};
Techically, index.js - is separate file, located in '/routes' folder. So, when I launch my app, it crashed cause can't find passport var, declared in main app. Also, ab also can't be found, however it was declared. If I re-declate vars in index.js, JS will create new objects for me. How can I use my vars in every module of my app? I looked through a few topics on SO, however couldn't understand – is it a common problem or just a structure of my app is wrong? Thanks!
As you have discovered, variables declared in one module don't magically appear in other modules. When it comes to modules such as passport, usually people just require them again where they're needed, so:
app.js:
var passport = require('passport'),
index = require('./routes/index');
index.js:
var passport = require('passport');
Sometimes you want to pass parameters though -- I often do it for unit testing, if I can pass in dependencies I can also mock those dependencies. Or you have an app-wide configuration you want to pass around. I usually do this:
app.js:
var ab = "foo",
index = require('/routes/index')(ab);
index.js:
module.exports = function(ab) {
// Here I have access to ab and can to what I need to do
return {
index: function(req, res) { res.send(ab) }
}
}
Other people prefer a "singleton" pattern, where each time you require a module, you check if it's already been initialized and if so, pass that instance.