3

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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, however let's imaging that I have up to 50 js-controllers, for every of my 50 pages. Most of them require passport, so it means i should declare it in every controller, such as index.js, about.js etc?
Yeah, either that or you pass it as a parameter. Standard practice is to require any modules that you need, locally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.