Skip to content

Instantly share code, notes, and snippets.

@arikon
Created March 13, 2015 20:09
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 arikon/74956e0a2aee53b3b790 to your computer and use it in GitHub Desktop.
Save arikon/74956e0a2aee53b3b790 to your computer and use it in GitHub Desktop.
Config reader based on node config module
var inherit = require('inherit'),
extend = require('extend');
module.exports = inherit({
__constructor: function(opts, overrides) {
// Remove config module from cache so it could be recreated.
// It's a limitation of the config module.
delete require.cache[require.resolve('config')];
resetEnvVars();
setEnvVars(opts);
var conf = require('config');
resetEnvVars();
if (overrides) {
conf = extend(true, conf, overrides);
}
return conf;
}
});
var envVars = [
'NODE_ENV',
'NODE_CONFIG_DIR',
'HOSTNAME',
'HOST',
'NODE_APP_INSTANCE',
'ALLOW_CONFIG_MUTATIONS',
'NODE_CONFIG_STRICT_MODE',
'SUPPRESS_NO_CONFIG_WARNING'
],
savedVars = {};
function saveEnvVars() {
envVars.forEach(function(v) {
if (typeof process.env[v] !== 'undefined') {
savedVars[v] = process.env[v];
}
});
}
function resetEnvVars() {
envVars.forEach(function(v) {
if (savedVars[v]) {
process.env[v] = savedVars[v];
} else {
delete process.env[v];
}
});
}
var optsEnvVarsMap = {
env: 'NODE_ENV',
configDir: 'NODE_CONFIG_DIR',
host: 'HOSTNAME',
instance: 'NODE_APP_INSTANCE'
};
function setEnvVars(opts) {
Object.keys(optsEnvVarsMap)
.forEach(function(key) {
if (typeof opts[key] !== 'undefined') {
process.env[optsEnvVarsMap[opts[key]]] = opts[key];
}
});
}
// Save config module related environment variables for later use
saveEnvVars();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment