Skip to content

Instantly share code, notes, and snippets.

@subfuzion
Created February 26, 2014 19:01
Show Gist options
  • Save subfuzion/9236115 to your computer and use it in GitHub Desktop.
Save subfuzion/9236115 to your computer and use it in GitHub Desktop.
Using nconf for Node application configuration

It's easy enough to load json files in Node, but what's nice about nconf is it neatly takes care of mundane issues and provides a nice way of hierarchically designating the precedences of settings. For example, it is trivial to specify that application args will override environment settings, which will override any configuration file settings, which will override any application defaults.

This is more of a memory aid to myself. It's best to check out the full documentation the first time through to familiarize yourself with all that nconf has to offer.

https://github.com/flatiron/nconf

npm install --save nconf

Using nconf

var nconf = require('nconf');

var filepath = './path/to/config.json';

var defaults = {
  db: {
    host : '127.0.0.1',
    port : '27017'
  }
};

nconf.argv()
     .env()
     .file({ file: filepath })
     .defaults(defaults)
     .overrides({ always: 'be this value'});

// retrieve db object
var db = nconf.get('db');

// explicitly set some variables:
nconf.set('db:host', '127.0.0.1');
nconf.set('db:host', '27017');

// save configuration to file
nconf.save(function(err) {
  if (err) console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment