public
Created

Node.js - merge environment variables + config file + command line args

  • Download Gist
config.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/**
* Merges environment variables + config file + command line args
*
* To use, from app.js:
* var conf = require('./config').init();
*/
var argv = require('optimist').argv;
 
function init() {
//1. check process.env
//2. config files override
//3. command line args final override
 
var vars = [
"GOOGLE_API_KEY",
"GOOGLE_CSE_ID",
"MONGODB_URI",
"LOGGLY_SUBDOMAIN",
"LOGGLY_INPUT_KEY"
];
var config = {};
var fileConfig = {};
try {
fileConfig = require('./conf/config.js');
} catch(e) {}
vars.forEach(function(el, idx, arr) {
config[el] = process.env[el];
if (fileConfig[el]) { config[el] = fileConfig[el]; }
if (argv[el]) { config[el] = argv[el]; }
});
return config;
 
}
 
exports.init = init;
template.js
JavaScript
1 2 3 4 5 6 7 8
//Fill in your accounts below and place in ./conf/config.js (see fileConfig var in config.js)
module.exports = {
GOOGLE_API_KEY: ""
, GOOGLE_CSE_ID: ""
, MONGODB_URI: ""
, LOGGLY_SUBDOMAIN: ""
, LOGGLY_INPUT_KEY: ""
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.