Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js make initialized object available in all modules

I have an initialized object that I initialized in app.js file and I would like to make this initialized object is available in all modules. How could I do that? Passing this object to every modules is one way to do and I'm wondering if I'm missing anything or there should be done in difference ways?

I saw mongoose actually support default connection, which I need to init in app.js one time and anywhere in other modules, I can just simply use it without requiring passing it around. Is there any I can do the same like this?

I also checked global object doc from node.js http://nodejs.org/api/globals.html, and wondering I should use global for issue.

Thanks

like image 409
Nam Nguyen Avatar asked Sep 06 '13 03:09

Nam Nguyen


2 Answers

A little advice:

  • You should only very rarely need to use a global. If you think you need one, you probably don't.
  • Singletons are usually an anti-pattern in Node.js, but sometimes (logging, config) they will get the job done just fine.
  • Passing something around is sometimes a useful and worthwhile pattern.

Here's an example of how you might use a singleton for logging:

lib/logger.js

var bunyan = require('bunyan'),
  mixIn = require('mout/object/mixIn'),

  // add some default options here...
  defaults = {},

  // singleton
  logger,

  createLogger = function createLogger(options) {
    var opts;

    if (logger) {
      return logger;
    }

    opts = mixIn({}, defaults, options);

    logger = bunyan.createLogger(opts);

    return logger;
  };

module.exports = createLogger;

lib/module.js

var logger = require('./logger.js'),
  log = logger();

log.info('Something happened.');

Hope that helps.

like image 53
Eric Elliott Avatar answered Nov 10 '22 23:11

Eric Elliott


The solution, as you suggest is to add the object as a property to the global object. However, I would recommend against doing this and placing the object in its own module that is required from every other module that needs it. You will gain benefits later on in several ways. For one, it is always explicit where this object comes from and where it is initialized. You will never have a situation where you try to use the object before it is initialized (assuming that the module that defines it also initializes it). Also, this will help make your code more testable,

like image 33
Andrew Eisenberg Avatar answered Nov 11 '22 00:11

Andrew Eisenberg