nconf

Hierarchical node.js configuration with files, environment variables, comma...

README

nconf


Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.

Example


Using nconf is easy; it is designed to be a simple key-value store with support for both local and remote storage. Keys are namespaced and delimited by :. Let's dive right into sample usage:

  1. ``` js
  2.   // sample.js
  3.   var nconf = require('nconf');

  4.   //
  5.   // Setup nconf to use (in-order):
  6.   //   1. Command-line arguments
  7.   //   2. Environment variables
  8.   //   3. A file located at 'path/to/config.json'
  9.   //
  10.   nconf.argv()
  11.    .env()
  12.    .file({ file: 'path/to/config.json' });

  13.   //
  14.   // Set a few variables on `nconf`.
  15.   //
  16.   nconf.set('database:host', '127.0.0.1');
  17.   nconf.set('database:port', 5984);

  18.   //
  19.   // Get the entire database object from nconf. This will output
  20.   // { host: '127.0.0.1', port: 5984 }
  21.   //
  22.   console.log('foo: ' + nconf.get('foo'));
  23.   console.log('NODE_ENV: ' + nconf.get('NODE_ENV'));
  24.   console.log('database: ' + nconf.get('database'));

  25.   //
  26.   // Save the configuration object to disk
  27.   //
  28.   nconf.save(function (err) {
  29.     require('fs').readFile('path/to/your/config.json', function (err, data) {
  30.       console.dir(JSON.parse(data.toString()))
  31.     });
  32.   });
  33. ```

If you run the below script:

  1. ``` shell
  2.   $ NODE_ENV=production node sample.js --foo bar
  3. ```

The output will be:

  1. ``` null
  2.   foo: bar
  3.   NODE_ENV: production
  4.   database: { host: '127.0.0.1', port: 5984 }

  5. ```

Hierarchical configuration


Configuration management can get complicated very quickly for even trivial applications running in production. nconfaddresses this problem by enabling you to setup a hierarchy for different sources of configuration with no defaults. The order in which you attach these configuration sources determines their priority in the hierarchy.Let's take a look at the options available to you

nconf.argv(options)Loads process.argvusing yargs. If optionsis supplied it is passed along to yargs.
nconf.env(options)Loads process.envinto the hierarchy.
nconf.file(options)Loads the configuration data at options.file into the hierarchy.
nconf.defaults(options)Loads the data in options.store into the hierarchy.
nconf.overrides(options)Loads the data in options.store into the hierarchy.

A sane default for this could be:

  1. ``` js
  2.   var nconf = require('nconf');

  3.   //
  4.   // 1. any overrides
  5.   //
  6.   nconf.overrides({
  7.     'always': 'be this value'
  8.   });

  9.   //
  10.   // 2. `process.env`
  11.   // 3. `process.argv`
  12.   //
  13.   nconf.env().argv();

  14.   //
  15.   // 4. Values in `config.json`
  16.   //
  17.   nconf.file('/path/to/config.json');

  18.   //
  19.   // Or with a custom name
  20.   // Note: A custom key must be supplied for hierarchy to work if multiple files are used.
  21.   //
  22.   nconf.file('custom', '/path/to/config.json');

  23.   //
  24.   // Or searching from a base directory.
  25.   // Note: `name` is optional.
  26.   //
  27.   nconf.file(name, {
  28.     file: 'config.json',
  29.     dir: 'search/from/here',
  30.     search: true
  31.   });

  32.   //
  33.   // 5. Any default values
  34.   //
  35.   nconf.defaults({
  36.     'if nothing else': 'use this value'
  37.   });
  38. ```

API Documentation


The top-level of nconfis an instance of the nconf.Providerabstracts this all for you into a simple API.

nconf.add(name, options)


Adds a new store with the specified nameand options. If options.typeis not set, then namewill be used instead:

  1. ``` js
  2.   nconf.add('supplied', { type: 'literal', store: { 'some': 'config' } });
  3.   nconf.add('user', { type: 'file', file: '/path/to/userconf.json' });
  4.   nconf.add('global', { type: 'file', file: '/path/to/globalconf.json' });
  5. ```

nconf.any(names, callback)


Given a set of key names, gets the value of the first key found to be truthy. The key names can be given as separate arguments or as an array. If the last argument is a function, it will be called with the result; otherwise, the value is returned.

  1. ``` js
  2.   //
  3.   // Get one of 'NODEJS_PORT' and 'PORT' as a return value
  4.   //
  5.   var port = nconf.any('NODEJS_PORT', 'PORT');

  6.   //
  7.   // Get one of 'NODEJS_IP' and 'IPADDRESS' using a callback
  8.   //
  9.   nconf.any(['NODEJS_IP', 'IPADDRESS'], function(err, value) {
  10.     console.log('Connect to IP address ' + value);
  11.   });
  12. ```

nconf.use(name, options)


Similar to nconf.add, except that it can replace an existing store if new options are provided

  1. ``` js
  2.   //
  3.   // Load a file store onto nconf with the specified settings
  4.   //
  5.   nconf.use('file', { file: '/path/to/some/config-file.json' });

  6.   //
  7.   // Replace the file store with new settings
  8.   //
  9.   nconf.use('file', { file: 'path/to/a-new/config-file.json' });
  10. ```

nconf.remove(name)


Removes the store with the specified name.The configuration stored at that level will no longer be used for lookup(s).

  1. ``` js
  2.   nconf.remove('file');
  3. ```

nconf.required(keys)


Declares a set of string keys to be mandatory, and throw an error if any are missing.

  1. ``` js
  2.   nconf.defaults({
  3.     keya: 'a',
  4.   });

  5.   nconf.required(['keya', 'keyb']);
  6.   // Error: Missing required keys: keyb
  7. ```

You can also chain .required()calls when needed. for example when a configuration depends on another configuration store

  1. ``` js
  2. config
  3.   .argv()
  4.   .env()
  5.   .required([ 'STAGE']) //here you should have STAGE otherwise throw an error
  6.   .file( 'stage', path.resolve( 'configs', 'stages', config.get( 'STAGE' ) + '.json' ) )
  7.   .required([ 'OAUTH:redirectURL']) // here you should have OAUTH:redirectURL, otherwise throw an error
  8.   .file( 'oauth', path.resolve( 'configs', 'oauth', config.get( 'OAUTH:MODE' ) + '.json' ) )
  9.   .file( 'app', path.resolve( 'configs', 'app.json' ) )
  10.   .required([ 'LOGS_MODE']) // here you should haveLOGS_MODE, otherwise throw an error
  11.   .add( 'logs', {
  12.     type: 'literal',
  13.     store: require( path.resolve( 'configs', 'logs', config.get( 'LOGS_MODE' ) + '.js') )
  14.   } )
  15.   .defaults( defaults );
  16. ```