Node.js Configuration

Node.js Configuration > config > Config
Search:
 
Filters

Class: Config

Runtime Application Configurations

The config module exports a singleton object representing all runtime configurations for this application deployment.

Application configurations are stored in files within the config directory of your application. The default configuration file is loaded, followed by files specific to the deployment type (development, testing, staging, production, etc.).

For example, with the following config/default.yaml file:

...
customer:
  initialCredit: 500
  db:
    name: customer
    port: 5984
...

The following code loads the customer section into the CONFIG variable:

var CONFIG = require('config').customer;
...
newCustomer.creditLimit = CONFIG.initialCredit;
database.open(CONFIG.db.name, CONFIG.db.port);
...

Methods

_attachProtoDeep

protected _attachProtoDeep ( toObject , depth )
Attach the Config class prototype to all config objects recursively.

This allows you to do anything with CONFIG sub-objects as you can do with the top-level CONFIG object. It's so you can do this:

var CUST_CONFIG = require('config').Customer;
CUST_CONFIG.watch(...)
Parameters:
toObject <object>
depth <object>

_cloneDeep

protected object _cloneDeep ( copyFrom , depth )
Return a deep copy of the specified object. This returns a new object with all elements copied from the specified object. Deep copies are made of objects and arrays so you can do anything with the returned object without affecting the input object.
Parameters:
copyFrom <object> The original object to copy from
depth <integer> An optional depth to prevent recursion. Default: 20.
Returns: object
A new object with the elements copied from the copyFrom object

_diffDeep

protected object _diffDeep ( object1 , object2 , depth )
Returns an object containing all elements that differ between two objects.

This method was designed to be used to create the runtime.json file contents, but can be used to get the diffs between any two Javascript objects.

It works best when object2 originated by deep copying object1, then changes were made to object2, and you want an object that would give you the changes made to object1 which resulted in object2.

Parameters:
object1 <object> The base object to compare to
object2 <object> The object to compare with
depth <integer> An optional depth to prevent recursion. Default: 20.
Returns: object
A differential object, which if extended onto object1 would result in object2.

_equalsDeep

protected boolean _equalsDeep ( object1 , object2 , depth )
Return true if two objects have equal contents.
Parameters:
object1 <object> The object to compare from
object2 <object> The object to compare with
depth <integer> An optional depth to prevent recursion. Default: 20.
Returns: boolean
True if both objects have equivalent contents

_extendDeep

protected object _extendDeep ( mergeInto , mergeFrom... , depth )
Extend an object, and any object it contains. This does not replace deep objects, but dives into them replacing individual elements instead.
Parameters:
mergeInto <object> The object to merge into
mergeFrom... <object...> - Any number of objects to merge from
depth <integer> An optional depth to prevent recursion. Default: 20.
Returns: object
The altered mergeInto object is returned

_getCmdLineArg

MIXED _getCmdLineArg ( searchFor )

Get Command Line Arguments

This method allows you to retrieve the value of the specified command line argument.

The argument is case sensitive, and must be of the form '--ARG_NAME=value'

Parameters:
searchFor <STRING> The argument name to search for
Returns: MIXED
FALSE if the argument was not found, the argument value if found

_initParam

Any _initParam ( paramName , [defaultValue] )

Initialize a parameter from the command line or process environment

This method looks for the parameter from the command line in the format --PARAMETER=VALUE, then from the process environment, then from the default specified as an argument.

Parameters:
paramName <String> Name of the parameter
[defaultValue] <Any> Default value of the parameter
Returns: Any
The found value, or default value

_isObject

protected boolean _isObject ( arg )
Is the specified argument a regular javascript object? The argument is an object if it's a JS object, but not an array.
Parameters:
arg <MIXED> An argument of any type.
Returns: boolean
TRUE if the arg is an object, FALSE if not

_loadFileConfigs

protected this _loadFileConfigs ( )
Load the individual file configurations.

This method builds a map of filename to the configuration object defined by the file. The search order is:

default.EXT
(hostname).EXT
(deployment).EXT
(hostname)-(deployment).EXT
local.EXT
local-(deployment).EXT
runtime.json

EXT can be yml, yaml, coffee, json, or js signifying the file type. yaml (and yml) is in YAML format, coffee is a coffee-script, json is in JSON format, and js is a javascript executable file that is require()'d with module.exports being the config object.

hostname is the $HOST environment variable (or --HOST command line parameter) if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command line parameter) if set, otherwise the hostname found from require('os').hostname().

Once a hostname is found, everything from the first period ('.') onwards is removed. For example, abc.example.com becomes abc

(deployment) is the deployment type, found in the $NODE_ENV environment variable or --NODE_ENV command line parameter. Defaults to 'development'.

The runtime.json file contains configuration changes made at runtime either manually, or by the application setting a configuration value.

If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE command line parameter) is set, then files with this appendage will be loaded. See the Multiple Applicstion Instances section of the main documentaion page for more information.

Returns: this
The configuration object

_loadOldStyleEnv

protected Object _loadOldStyleEnv ( )
Check for the old-style environment variable configurations
Returns: Object
old-style configurations from process.env
Deprecated  

_parseFile

protected configObject _parseFile ( fullFilename )
Parse and return the specified configuration file. If the file exists in the application config directory, it will parse and return it as a JavaScript object. The file extension determines the parser to use. .js = File to run that has a module.exports containing the config object .json = File is parsed using JSON.parse() .coffee = File to run that has a module.exports with coffee-script containing the config object .yaml (or .yml) = Parsed with a YAML parser If the file doesn't exist, a null will be returned. If the file can't be parsed, an exception will be thrown. This method performs synchronous file operations, and should not be called after synchronous module loading.
Parameters:
fullFilename <string> The full file path and name
Returns: configObject
The configuration object parsed from the file

_persistConfigsOnChange

protected void _persistConfigsOnChange ( object )

Watch the specified object for a change in properties, and persist changes to runtime.json when a change is detected.

Parameters:
object <object> - The config object to watch
Returns: void

_stripComments

protected string _stripComments ( fileString )
Strip all Javascript type comments from the string. The string is usually a file loaded from the O/S, containing newlines and javascript type comments. Thanks to James Padolsey, and all who conributed to this implementation. http://james.padolsey.com/javascript/javascript-comment-removal-revisted/
Parameters:
fileString <string> The string to strip comments from
Returns: string
The string with comments stripped.

_stripYamlComments

protected string _stripYamlComments ( fileString )
Strip YAML comments from the string The 2.0 yaml parser doesn't allow comment-only or blank lines. Strip them.
Parameters:
fileString <string> The string to strip comments from
Returns: string
The string with comments stripped.

constructor

object constructor ( )

Get the configuration object.

The configuration object is a shared singleton object within the applicaiton, attained by calling require('config').

Usually you'll specify a CONFIG variable at the top of your .js file for file/module scope. If you want the root of the object, you can do this:

var CONFIG = require('config');

Sometimes you only care about a specific sub-object within the CONFIG object. In that case you could do this at the top of your file:

var CONFIG = require('config').customer;
or
var CUSTOMER_CONFIG = require('config').customer;
Returns: object
CONFIG - The top level configuration object

getConfigSources

Array[Object] getConfigSources ( )
Return the sources for the configurations

All sources for configurations are stored in an array of objects containing the source name (usually the filaname), the original source (as a string), and the parsed source as an object.

Returns: Array[Object]
configSources - An array of objects containing name, original, and parsed elements

getOriginalConfig

object getOriginalConfig ( )

Exposing original Config

This method allows get the original config properties.

Returns: object
The original config object is returned

makeHidden

object makeHidden ( object , property , value )

Make a configuration property hidden so it doesn't appear when enumerating elements of the object.

The property still exists and can be read from and written to, but it won't show up in for ... in loops, Object.keys(), or JSON.stringify() type methods.

If the property already exists, it will be made hidden. Otherwise it will be created as a hidden property with the specified value.

This method was built for hiding configuration values, but it can be applied to any javascript object.

Example:

var CONFIG = require('config');
...
// Hide the Amazon S3 credentials
CONFIG.makeHidden(CONFIG.amazonS3, 'access_id');
CONFIG.makeHidden(CONFIG.amazonS3, 'secret_key');
Parameters:
object <object> - The object to make a hidden property into.
property <string> - The name of the property to make hidden.
value <mixed> - (optional) Set the property value to this (otherwise leave alone)
Returns: object
object - The original object is returned - for chaining.

makeImmutable

object makeImmutable ( object , property , value )

Make a configuration property immutable (assuring it cannot be changed from the current value).

This operation cannot be un-done.

This method was built for disabling runtime changes to configuration values, but it can be applied to any javascript object.

Example:

var CONFIG = require('config').customer;
...
// Obtain a DB connection using CONFIG parameters
database.open(CONFIG.db.name, CONFIG.db.port);
...
// Don't allow database changes after connect
CONFIG.makeImmutable(CONFIG.db, 'name');
CONFIG.makeImmutable(CONFIG.db, 'port');
Parameters:
object <object> - The object to attach an immutable property into.
property <string> - The name of the property to make immutable.
value <mixed> - (optional) Set the property value to this (otherwise leave alone)
Returns: object
object - The original object is returned - for chaining.

resetRuntime

void resetRuntime ( callback )

Reset Runtime Config

This method allows you to reset the runtime.json generated file.

Parameters:
callback <function> An optional callback function
Returns: void

setModuleDefaults

object setModuleDefaults ( moduleName , defaultProperties )

Set default configurations for a node.js module.

This allows module developers to attach their configurations onto the default configuration object so they can be configured by the consumers of the module.

Using the function within your module:

var CONFIG = require("config");
CONFIG.setModuleDefaults("MyModule", {
  templateName: "t-50",
  colorScheme: "green"
});

// Template name may be overridden by application config files console.log("Template: " + CONFIG.MyModule.templateName);

The above example results in a "MyModule" element of the configuration object, containing an object with the specified default values.

Parameters:
moduleName <string> - Name of your module.
defaultProperties <object> - The default module configuration.
Returns: object
moduleConfig - The module level configuration object.

watch

object watch ( object , property , handler , depth )

Monitor a configuration value for runtime changes.

Configuration values can be changed at runtime by the application or by a manual change to the config/runtime.json file. This method lets you specify a function to run when a configuration value changes.

This was built for monitoring changes to configuration values, but it can be used for watching changes to any javascript object.

Example:

var CONFIG = require('config').customer;
...
// Watch for any changes to the customer configuration
CONFIG.watch(CONFIG, null, function(object, propertyName, priorValue, newValue) {
 console.log("Customer configuration " + propertyName + " changed from " + priorValue + " to " + newValue);
});
Parameters:
object <object> - The object to watch.
property <string> - The property name to watch. Watch all object properties if null.
handler <function(object, propertyName, priorValue, newValue)> - Handler called when a property change is detected. The handler is run along with other handlers registered for notification. If your handler changes the value of the property, that change is applied after all handlers have finished processing the current change. Then all handlers (including this one) will be called again with the newly changed value.
depth <integer> (optional) - If watching all object properties or if the specified property is an object, this specifies the depth of the object graph to watch for changes. Default 6.
Returns: object
object - The original object is returned - for chaining.

watchForConfigFileChanges

void watchForConfigFileChanges ( interval )
Start or stop runtime.json configuration file watching

Node-config automatically monitors and apply changes made to the config/runtime.json file. This paradigm allows for manual changes to running application servers, and for multi-node application servers to keep in sync.

This method allows you to change the polling interval from the default interval (2.5 seconds), or to turn file watching off. On Linux systems with inotify, and in node.js versions 0.6 and above, this interval is ignored.

runtime.json file watching can be disabled by setting the NODE_CONFIG_DISABLE_FILE_WATCH environment variable or --NODE_CONFIG_DISABLE_FILE_WATCH command line parameter to "Y" prior to running your application.

Parameters:
interval <Integer> - Polling interval in milliseconds. Defaults to 2500.
Returns: void


Released on github under the Apache License 2.0 version 0.4.32