Tag Archives: nconf

Using nconf to manage configuration

Managing configuration is one of the most important part of software release. we always have different production,development and quality environment having flexibility to point to any of these environment with no or very less change in the source code is highly desirable feature. I was looking for a solution that can help me achieve this at same point does not break my code if i decide to change the underline configuration file location.

nconf is a nodejs module that helps in organizing configuration quickly by providing integration with environment variables,arguments and a configuration file (config.json). Depending on the order in which we have configured the sources they take precedence over each other.

This blog post focuses on using nconf with a configuration file and also reading arguments from command line using argv
Our config.json looks like


We declared two properties in config.json. To read these properties in our .js file we need to first require the nconf module and then add the config file. Once done we can access the key/value pairs using get,set,remove methods

var nconf=require('nconf');
var fs=require('fs');
var nconfargv=nconf.argv();
// Setup nconf to use the 'file' store and set a couple of values;
nconf.add('file', { file: 'config.json' });
// overrides the database host value
// Save the configuration object to disk
nconf.save(function (err) {
fs.readFile('config.json', function (err, data) {
// console.dir(JSON.parse(data.toString()))

Running the above code using

node .js

results in printed on console. As we have also used argv() with nconf to get the reference of command line arguments passed. If we run our App using

node .js --DATABASE_HOST localhost

we get localhost printed on console.It is that easy to switch between different environments and different configuration options available using nconf.