2

I have a configuration file (simplified below) for a Node.JS app

module.exports = function(){
  var settings = {
    port: '8088'
  }; 
  settings.mysql = {
    host : 'localhost',
    database : 'test'
  };
  // Override default settings
  switch(process.env.NODE_ENV){
    case 'production':
      settings.port = 8082;
    break;
    case 'staging':
      settings.port = 8083;
    break;     
  }
  return settings;
};

When I start my Express.js application I require this file for some basic settings:

var Config = require('./config'),  settings = new Config();
var port = process.env.PORT || settings.port;    // set our port

I also need to use the MySQL settings in this file later on within a DAO(in my model). At that point I call the configuration file (which will run it again)

var Config = require('../config'), settings = new Config();
var mysql = require('mysql');
var pool = mysql.createPool(settings.mysql);

Obviously each time I "require" the file gets run, this just seem lazy/inefficient. Should I be storing the returned "settings" variable in a global variable which my DAO can see, or should I be passing it in by reference?

I did at one point think about making it middleware and add it the REQUEST but then I would need my route (controller) to all pass it in to the DAO (model) which doesn't feel right.

Andy Jarrett
  • 863
  • 2
  • 9
  • 26

1 Answers1

5

Just export the object itself instead of wrapping it in a function - Node modules get cached after the first load, so it won't run the logic again.

var settings = {
  port: '8088'
}; 

settings.mysql = {
  host : 'localhost',
  database : 'test'
};

// Override default settings
switch(process.env.NODE_ENV){
  case 'production':
    settings.port = 8082;
  break;
  case 'staging':
    settings.port = 8083;
  break;     
}

module.exports = settings;
Joe Clay
  • 33,401
  • 4
  • 85
  • 85
  • I'm not sure how the cache works exactly (and I'm too lazy to check right now), but I wouldn't be surprised if it worked even with the function, as it's probably the `module` that gets cached. – jcaron Feb 05 '16 at 10:20
  • The problem is more likely to be with the differing path, not sure if node canonicalises paths (to a full path) or uses it as is. – jcaron Feb 05 '16 at 10:21
  • @jcaron - I'd imagine the function probably would get cached, but it still seems silly to have to rerun it every time to get the same result. But you're right, I'm not 100% sure how the caching interacts with different relative paths, I'll have to look into that! – Joe Clay Feb 05 '16 at 10:35
  • @jcaron - Yep, modules are cached using an absolute path rather than the one used to `require` them, so relative paths shouldn't cause separate objects to be returned! http://stackoverflow.com/a/15666221/5436257 – Joe Clay Feb 05 '16 at 10:55