Skip to content

Instantly share code, notes, and snippets.

@cbumgard
Created November 15, 2012 02:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cbumgard/4076234 to your computer and use it in GitHub Desktop.
Save cbumgard/4076234 to your computer and use it in GitHub Desktop.
Dynamic config module for node.js apps to simplify managing configurations for different environments. Reads in a config file matching the current NODE_ENV.
// This module loads a config file in the current working directory matching the NODE_ENV variable.
// I.e. either './development.js' or './production.js' based on the process.env.NODE_ENV variable.
// If not set, it defaults to './development.js'.
// Can load custom environment files as well, as long as the NODE_ENV variable matches
// a file in the current directory. E.g. './staging.js'
// Usage: calling code can just require this module, e.g. "var config = require('./config')"
// assuming this file is named "index.js" and lives in a subdirectory named "config" of the app root.
var config
, config_file = './' + (process.env.NODE_ENV ? process.env.NODE_ENV : 'development') + '.js';
try {
config = require(config_file);
} catch (err) {
if (err.code && err.code === 'MODULE_NOT_FOUND') {
console.error('No config file matching NODE_ENV=' + process.env.NODE_ENV
+ '. Requires "' + __dirname + '/' + process.env.NODE_ENV + '.js"');
process.exit(1);
} else {
throw err;
}
}
module.exports = config;
@meaku
Copy link

meaku commented May 15, 2014

Nice gist. I wrote a module which does almost what you do, but it accepts an "env" to be passed via args optionally.

Maybe it helps :)
https://github.com/peerigon/dynamic-config

I will add the check for NODE_ENV soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment