Skip to content

Instantly share code, notes, and snippets.

@EyalAr
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EyalAr/3bc1c209f3d10c70692d to your computer and use it in GitHub Desktop.
Save EyalAr/3bc1c209f3d10c70692d to your computer and use it in GitHub Desktop.
Generic configuration parser for my Node.js projects. Allows to override selectively with environment variables.
module.exports = {
key1: 'foo',
key2: {
subkey1: 'foo',
subkey2: {
subsubkey1: 'foo',
// ...
}
}
}
// Generic configuration parser for my Node.js projects.
//
// https://gist.github.com/EyalAr/3bc1c209f3d10c70692d
//
// Allows to override selectively with environment variables.
// Your configuration will be overridden by environment variables if:
// 1. [envPrefix]_ENV_OVERRIDE is set
// or:
// 2. [envPrefix]_ENV is set and not 'development'
//
// Environment variables structure:
// conf.key1 ==> MY_APP_KEY1
// conf.key1.subkey2 ==> MY_APP_KEY1_SUBKEY2
// conf.key1.subkey2.subsubkey3 ==> MY_APP_KEY1_SUBKEY2_SUBSUBKEY3
module.exports = function(envPrefix, confFile) {
var resolve = require('path').resolve,
conf = require(resolve(process.cwd(), confFile)),
res = {};
// override with environment variables if:
// 1. [envPrefix]_ENV_OVERRIDE is set
// or:
// 2. [envPrefix]_ENV is set and not 'development'
var envOverride = !!process.env[envPrefix + '_ENV_OVERRIDE'] || (process.env[envPrefix + '_ENV'] && process.env[envPrefix + '_ENV'] !== 'development');
if (!envOverride) return conf;
traverse(conf, []);
return res;
function setVal(obj, path, val) {
var first = path.shift();
if (path.length === 0) return obj[first] = val;
if (typeof obj[first] !== 'object') obj[first] = {};
setVal(obj[first], path, val);
}
function traverse(obj, path) {
Object.keys(obj).forEach(function(key) {
var val = obj[key],
kPath = [key];
Array.prototype.unshift.apply(kPath, path);
if (typeof val !== 'object') {
// corresponding environment variable:
var eVar = (envPrefix + '_' + kPath.join('_')).toUpperCase();
// override if defined
if (process.env[eVar]) {
console.log('Conf: Using env var', eVar);
val = process.env[eVar];
}
setVal(res, kPath, val);
} else {
traverse(val, kPath);
}
});
}
}
// let's say the following env vars are set:
// MY_APPY_ENV=staging
// MY_APP_KEY1=bar
var confParser = require('./confParser'),
conf = confParser('MY_APP', './conf.example.js');
// conf.key1 === 'bar'
// conf.key2.subkey1 === 'foo'
// conf.key2.subkey2.subsubkey1 === 'foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment