You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Mark Stosberg edited this page May 30, 2025
·
10 revisions
Files ending in .js and .cjs (as of 3.4.0) are loaded and run as a CommonJS JavaScript module. The module must export the configuration object. Some folks appreciate the ability to compute configurations, others feel it's not the right thing to do. It's nice to live in a world with choice.
JavaScript modules support the ability to have "deferred" and "raw" values.
Loading files as ESM is not yet supported. So .mjs or .js when "type":"module" or --experimental-modules will not work.
Deferred values in JavaScript configuration files
In the JavaScript modules you have the option to define a configuration value as a function whose resolution
will be deferred until the final merged configuration structure is built.
For example, you set up a default value for a "full name" that is calculated from "first name" and "last name" values which will be provided a config file which overrides the defaults.
Example:
// In default.js// using defer functions is optional. See example and docs below.vardefer=require('config/defer').deferConfig;module.exports={firstName : undefined,lastName: undefined,fullName : defer(function(){returnthis.firstName+' '+this.lastName;})}
Because the resolution of fullName is deferred, it would resolve to refer to the overridden first and last name.
In addition to setting the this value of the function to the config option, it also receives two arguments: The config object is also available as the first argument, and the original, or parent, value of the current value is available as the second argument. This allows a defer function to reference it's own default value without creating an infinite loop. For example, perhaps in the qa environment you want to extend the "test" property which is defined as an array in config/default.js. Then you could use:
// in config/default.jsmodule.exports={"test": ["a_string"],}// in config/qa.jsconstdefer=require('config/defer').deferConfig;// Extend the parent's arraymodule.exports={test: defer(function(config,original){returnoriginal.concat('boom');}),}
The use of ECMAScript 5 getters in JavaScript configurations is not supported. Using deferred configuration values is the recommended alternative.
Using process.stdout and other objects in JavaScript config files
There may be instances where you would like to place a complex object like process.stdout into your configuration file, e.g. logging configuration. But node-config achieves its useful functionality by modifying the config object prototypes then making them immutable - not ideal for process.stdout! But you can still achieve the goal by using the raw functionality like so: