Skip to content

Instantly share code, notes, and snippets.

@brickpop
Last active November 16, 2016 16:30
Show Gist options
  • Save brickpop/7854fdc440300d162f7759a5a5c1e04a to your computer and use it in GitHub Desktop.
Save brickpop/7854fdc440300d162f7759a5a5c1e04a to your computer and use it in GitHub Desktop.
Example of a dev/production/env config system for NodeJS
// These are de default settings
// They may be overriden by the values in cofig-production.js if NODE_ENV=production
// They may also be averriden if an environment variable with the same name is set
// WARNING: Do not include this file directly. Use config.js instead
module.exports = {
DEBUG: true,
COMPONENT_NAME: 'PROJECT API',
HTTP_PORT: 8000,
MONGODB_URI: 'mongodb://mongo:27017/app'
};
// These settings will apply only if NODE_ENV='production'
// They may be averriden if an environment variable with the same name is set
// WARNING: Do not include this file directly. Use config.js instead
module.exports = {
DEBUG: false,
HTTP_PORT: 80
};
// Example usage assuming HTTP_PORT is set in config-default.js or in config-production.js:
//
// if API_HTTP_PORT is set as an environment variable, config.HTTP_PORT will take its value
// else if HTTP_PORT is set as an environment variable, config.HTTP_PORT will take its value
// else if NODE_ENV=production and config-production.js contains the key, config.HTTP_PORT will take its value
// else config.HTTP_PORT will take de value defined in config-default.js
//
// NOTE: Only keys defined in config-*.js will be used
// Other environment variables will be ignored
//
const VAR_PREFIX = "API_";
const defaultConfig = require('./config-default.js');
const productionConfig = require('./config-production.js');
var config = {};
// Base config
if(process.env.NODE_ENV == 'production') {
console.log("Config.js is using production settings");
config = Object.assign(config, defaultConfig, productionConfig);
}
else {
config = defaultConfig;
}
// Environment variables will override existing keys
Object.keys(config).forEach(key => {
if(typeof process.env[VAR_PREFIX + key] != 'undefined') {
console.log("Using ENV variable", VAR_PREFIX + key);
config[key] = process.env[VAR_PREFIX + key];
}
else if(typeof process.env[key] != 'undefined') {
console.log("Using ENV variable", key);
config[key] = process.env[key];
}
}, {});
module.exports = config;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment