How to make object references available in Node modules?

I have an Express.js web app. In the main app.js file, I require() a bunch of third party dependencies. Recently I've started extracting parts of my app.js code into separate modules, e.g.

// in app.js
var users = require('./modules/users');

// and then e.g.
// users.add(doc);

Inside my modules, I sometimes need to use objects that are available in my main app.js file and I'm wondering what's the best way to pass references to those object to my modules.

My current approach:

// in app.js

// pass needed object references in initialization step
users.init([db, logger]);

and

// in modules/users.js

var db, logger;

exports.init = function (deps) {
    db = deps[0];
    logger = deps[1];
};

Does this approach make sense? Is there a better way to perform this?

Sure, just use modules! :)

// db.js

// create db instance here rather than in app.js

module.exports = db;

And

// logger.js

// create logger instance here rather than in app.js

module.exports = logger;

Then

// app.js

var db = require('./db');

And

// lib/somewhere.js

var db = require('../db');

This way you're able to rely on the CommonJS dependency injection system rather than on doing the dependency injection all by yourself (passing references around instead of requireing a module into yours).

The reason why this works as expected is that modules are only interpreted once, so if you instantiate everything once as opposed to using a factory function, it just works.

You should just be able to require modules as normal:

// users.js
var db = require('./db');
exports.init = function() {
   // use db in here
};

However, sometimes this isn't possible and you will need to explicitly pass in the module. One way to do it is to pass in dependencies when you require the module:

// users.js
module.exports = function(db, logger) {
    return {
        init: function() { /* use db and logger in here */}
    }; 
}

// app.js
var db = ...;
var logger = ...;
var users = require('./users')(db, logger);
users.init();

This is the pattern that I personally prefer, I think it's cleaner to pass dependencies into the require than into some init method like you have in your example.

You'll see this done in ExpressJS code quite a lot, for example when we have all our routes in another file and need to pass our app instance around:

require('./routes')(app);

If you need something to be initialized specifically in app.js rather than their own module you can export them from app.js and then require app.js:

// app.js
var db = require("db"),
    logger = require("logger");

// do your initialization with db and logger
module.exports = { db: db, logger: logger };

and then:

// users.js
var db = require("./app").db,
    logger = require("./app").logger;

// use db and logger

This works because as @Nico mentioned, modules are interpreted once and app.js will not be interpreted each time it is required from elsewhere.