Search code examples
javascriptmysqlnode.jsnode-mysql

Best way to use a configuration file in Node.JS


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.


Solution

  • 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;