What is nconf?
nconf is a hierarchical node.js configuration with support for multiple sources. It allows you to manage configuration settings for your application from various sources such as command-line arguments, environment variables, files, and even custom sources.
What are nconf's main functionalities?
Loading Configuration from Command-Line Arguments
This feature allows you to load configuration settings from command-line arguments. The `argv` method parses the command-line arguments and makes them available through the `nconf` object.
const nconf = require('nconf');
nconf.argv();
console.log(nconf.get('someArg'));
Loading Configuration from Environment Variables
This feature allows you to load configuration settings from environment variables. The `env` method reads the environment variables and makes them accessible through the `nconf` object.
const nconf = require('nconf');
nconf.env();
console.log(nconf.get('NODE_ENV'));
Loading Configuration from a File
This feature allows you to load configuration settings from a file. The `file` method reads the specified file and makes its contents available through the `nconf` object.
const nconf = require('nconf');
nconf.file({ file: 'config.json' });
console.log(nconf.get('database:host'));
Setting Default Values
This feature allows you to set default configuration values. The `defaults` method sets the default values that will be used if no other source provides a value for a given key.
const nconf = require('nconf');
nconf.defaults({ 'port': 3000 });
console.log(nconf.get('port'));
Overriding Configuration Values
This feature allows you to override configuration values. The `overrides` method sets values that will take precedence over any other source.
const nconf = require('nconf');
nconf.overrides({ 'port': 8080 });
console.log(nconf.get('port'));
Other packages similar to nconf
config
The `config` package provides a way to manage configuration files for your Node.js application. It supports different configurations for different deployment environments and allows for hierarchical configurations. Compared to nconf, `config` is more focused on file-based configurations and environment-specific settings.
dotenv
The `dotenv` package loads environment variables from a `.env` file into `process.env`. It is simpler and more lightweight compared to nconf, focusing solely on environment variables and not supporting other sources like command-line arguments or JSON files.
convict
The `convict` package provides a way to define a schema for your configuration and validate it. It supports multiple sources like environment variables and JSON files, similar to nconf. However, `convict` adds the ability to define a schema and validate the configuration against it, which nconf does not provide.
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 :
. Lets dive right into sample usage:
var fs = require('fs'),
nconf = require('nconf');
nconf.argv()
.env()
.file({ file: 'path/to/config.json' });
nconf.set('database:host', '127.0.0.1');
nconf.set('database:port', 5984);
console.log('foo: ' + nconf.get('foo'));
console.log('NODE_ENV: ' + nconf.get('NODE_ENV'));
console.log('database: ' + nconf.get('database'));
nconf.save(function (err) {
fs.readFile('path/to/your/config.json', function (err, data) {
console.dir(JSON.parse(data.toString()))
});
});
If you run the above script:
$ NODE_ENV=production sample.js --foo bar
The output will be:
foo: bar
NODE_ENV: production
database: { host: '127.0.0.1', port: 5984 }
Hierarchical configuration
Configuration management can get complicated very quickly for even trivial applications running in production. nconf
addresses 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. Lets take a look at the options available to you
- nconf.argv(options) Loads
process.argv
using optimist. If options
is supplied it is passed along to optimist. - nconf.env(options) Loads
process.env
into 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:
var nconf = require('nconf');
nconf.overrides({
'always': 'be this value'
});
nconf.env().argv();
nconf.file({ file: 'config.json' });
nconf.defaults({
'if nothing else': 'use this value'
});
API Documentation
The top-level of nconf
is an instance of the nconf.Provider
abstracts this all for you into a simple API.
nconf.add(name, options)
Adds a new store with the specified name
and options
. If options.type
is not set, then name
will be used instead:
nconf.add('user', { type: 'file', file: '/path/to/userconf.json' });
nconf.add('global', { type: 'file', file: '/path/to/globalconf.json' });
nconf.use(name, options)
Similar to nconf.add
, except that it can replace an existing store if new options are provided
nconf.use('file', { file: '/path/to/some/config-file.json' });
nconf.use('file', { file: 'path/to/a-new/config-file.json' });
nconf.remove(name)
Removes the store with the specified name.
The configuration stored at that level will no longer be used for lookup(s).
nconf.remove('file');
Storage Engines
Memory
A simple in-memory storage engine that stores a nested JSON representation of the configuration. To use this engine, just call .use()
with the appropriate arguments. All calls to .get()
, .set()
, .clear()
, .reset()
methods are synchronous since we are only dealing with an in-memory object.
nconf.use('memory');
Argv
Responsible for loading the values parsed from process.argv
by optimist
into the configuration hierarchy.
nconf.argv(options);
Env
Responsible for loading the values parsed from process.env
into the configuration hierarchy.
nconf.env(['only', 'load', 'these', 'values', 'from', 'process.env']);
Literal
Loads a given object literal into the configuration hierarchy. Both nconf.defaults()
and nconf.overrides()
use the Literal store.
nconf.defaults({
'some': 'default value'
});
File
Based on the Memory store, but provides additional methods .save()
and .load()
which allow you to read your configuration to and from file. As with the Memory store, all method calls are synchronous with the exception of .save()
and .load()
which take callback functions. It is important to note that setting keys in the File engine will not be persisted to disk until a call to .save()
is made.
nconf.file({ file: 'path/to/your/config.json' });
The file store is also extensible for multiple file formats, defaulting to JSON
. To use a custom format, simply pass a format object to the .use()
method. This object must have .parse()
and .stringify()
methods just like the native JSON
object.
Redis
There is a separate Redis-based store available through nconf-redis. To install and use this store simply:
$ npm install nconf
$ npm install nconf-redis
Once installing both nconf
and nconf-redis
, you must require both modules to use the Redis store:
var nconf = require('nconf');
require('nconf-redis');
nconf.use('redis', { host: 'localhost', port: 6379, ttl: 60 * 60 * 1000 });
Installation
Installing npm (node package manager)
curl http://npmjs.org/install.sh | sh
Installing nconf
[sudo] npm install nconf
More Documentation
There is more documentation available through docco. I haven't gotten around to making a gh-pages branch so in the meantime if you clone the repository you can view the docs:
open docs/nconf.html
Run Tests
Tests are written in vows and give complete coverage of all APIs and storage engines.
$ npm test
License: MIT