Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core configuration operations providing hierarchical access to configuration data with support for nested keys, multiple data sources, and both synchronous and asynchronous operations.
Retrieve configuration values with hierarchical lookup across all configured stores in priority order.
/**
* Retrieve configuration value for the specified key
* @param {string|function} [key] - Configuration key (supports nested keys with ':' delimiter), or callback for full config
* @param {function} [callback] - Optional callback for async operation
* @returns {*} Configuration value or undefined if not found
*/
get(key, callback);Usage Examples:
const nconf = require('nconf');
// Synchronous get
const dbHost = nconf.get('database:host');
const port = nconf.get('server:port');
const config = nconf.get('database'); // Gets entire nested object
// Get root configuration
const allConfig = nconf.get();
// Asynchronous get
nconf.get('database:host', (err, value) => {
if (err) console.error('Error:', err);
else console.log('Database host:', value);
});
// Get with nested object merging across stores
nconf.get('database', (err, dbConfig) => {
// Merges database config from all stores
console.log(dbConfig); // { host: 'localhost', port: 5432, ssl: true }
});Set configuration values with automatic nested object creation and hierarchical key support.
/**
* Set configuration value for the specified key
* @param {string} key - Configuration key (supports nested keys with ':' delimiter)
* @param {*} value - Value to set (can be primitive, object, or array)
* @param {function} [callback] - Optional callback for async operation
* @returns {Provider} Provider instance for chaining
*/
set(key, value, callback);Usage Examples:
// Set simple values
nconf.set('app:name', 'MyApp');
nconf.set('app:version', '1.0.0');
// Set nested objects
nconf.set('database', {
host: 'localhost',
port: 5432,
ssl: true
});
// Set array values
nconf.set('app:features', ['auth', 'logging', 'metrics']);
// Chaining operations
nconf
.set('app:env', 'production')
.set('app:debug', false)
.set('app:timeout', 30000);
// Asynchronous set
nconf.set('cache:ttl', 3600, (err) => {
if (err) console.error('Error setting cache TTL:', err);
else console.log('Cache TTL set successfully');
});Remove configuration keys and their values from all writable stores.
/**
* Remove configuration key and its value
* @param {string} key - Configuration key to remove
* @param {function} [callback] - Optional callback for async operation
* @returns {Provider} Provider instance for chaining
*/
clear(key, callback);Usage Examples:
// Clear specific key
nconf.clear('database:password');
// Clear nested object
nconf.clear('temp:cache');
// Asynchronous clear
nconf.clear('session:tokens', (err) => {
if (err) console.error('Error clearing tokens:', err);
else console.log('Session tokens cleared');
});Merge objects into existing configuration with deep merging support and automatic nested key creation.
/**
* Merge object into existing configuration
* @param {string} [key] - Target key to merge into, or merge into root if not provided
* @param {Object} value - Object to merge (must be an object)
* @param {function} [callback] - Optional callback for async operation
* @returns {Provider} Provider instance for chaining
*/
merge(key, value, callback);Usage Examples:
// Merge into specific key
nconf.merge('database', {
pool: { min: 2, max: 10 },
timeout: 5000
});
// Merge into root (two-parameter form)
nconf.merge({
app: { name: 'MyApp' },
server: { host: '0.0.0.0' }
});
// Merge with callback
nconf.merge('api:settings', {
rateLimit: 1000,
timeout: 30000
}, (err) => {
if (err) console.error('Merge failed:', err);
else console.log('API settings merged successfully');
});
// Deep merging behavior
nconf.set('existing', { a: 1, b: { x: 10 } });
nconf.merge('existing', { b: { y: 20 }, c: 3 });
// Result: { a: 1, b: { x: 10, y: 20 }, c: 3 }Get the first truthy value from a list of configuration keys, useful for fallback scenarios.
/**
* Get first truthy value from a list of keys
* @param {string[]|...string} keys - Array of keys or variable arguments
* @param {function} [callback] - Optional callback for async operation
* @returns {*} First truthy value found or null if none found
*/
any(keys, callback);Usage Examples:
// Array form
const host = nconf.any(['DB_HOST', 'DATABASE_HOST', 'db:host']);
// Variable arguments form
const port = nconf.any('DB_PORT', 'DATABASE_PORT', 'db:port', 'DEFAULT_PORT');
// With default fallback
const timeout = nconf.any(['API_TIMEOUT', 'app:timeout']) || 5000;
// Asynchronous form
nconf.any(['redis:url', 'REDIS_URL', 'cache:redis'], (err, value) => {
if (err) console.error('Error finding Redis URL:', err);
else console.log('Redis URL:', value || 'not found');
});Validate that required configuration keys are present, throwing an error if any are missing.
/**
* Validate that required configuration keys are present
* @param {string[]} keys - Array of required key names
* @throws {Error} Throws error with missing key names if validation fails
* @returns {boolean} Returns true if all keys are present
*/
required(keys);Usage Examples:
// Validate required keys
try {
nconf.required(['database:host', 'database:port', 'app:secret']);
console.log('All required configuration present');
} catch (err) {
console.error('Missing required configuration:', err.message);
process.exit(1);
}
// In application startup
const requiredKeys = [
'DATABASE_URL',
'JWT_SECRET',
'API_KEY',
'app:name'
];
if (nconf.required(requiredKeys)) {
// Safe to start application
startServer();
}Clear all configuration data from all writable stores.
/**
* Clear all configuration data
* @param {function} [callback] - Optional callback for async operation
* @returns {Provider} Provider instance for chaining
*/
reset(callback);Usage Examples:
// Synchronous reset
nconf.reset();
// Asynchronous reset
nconf.reset((err) => {
if (err) console.error('Error resetting configuration:', err);
else console.log('Configuration reset successfully');
});
// Reset and reload
nconf.reset().load((err) => {
if (err) console.error('Error reloading after reset:', err);
else console.log('Configuration reset and reloaded');
});Add a literal store containing default configuration values with lowest priority in the hierarchy.
/**
* Add default configuration values (lowest priority store)
* @param {Object} options - Default configuration object or store options
* @returns {Provider} Provider instance for chaining
*/
defaults(options);Usage Examples:
// Add default values
nconf.defaults({
app: {
name: 'MyApp',
version: '1.0.0',
debug: false,
port: 3000
},
database: {
host: 'localhost',
port: 5432,
timeout: 30000
}
});
// With store options
nconf.defaults({
type: 'literal',
store: {
server: { host: '127.0.0.1', port: 8080 },
cache: { enabled: true, ttl: 300 }
}
});
// Chaining with hierarchy
nconf
.argv() // Highest priority
.env() // Second priority
.file('./config.json') // Third priority
.defaults({ // Lowest priority
env: 'development',
debug: true
});Add a literal store containing override configuration values with highest priority in the hierarchy.
/**
* Add override configuration values (highest priority store)
* @param {Object} options - Override configuration object or store options
* @returns {Provider} Provider instance for chaining
*/
overrides(options);Usage Examples:
// Add override values (always take precedence)
nconf.overrides({
app: {
env: 'production', // Always production regardless of other sources
debug: false // Always disable debug in production
},
security: {
enabled: true // Security always enabled
}
});
// With store options
nconf.overrides({
type: 'literal',
store: {
'always': 'this value',
'never': 'changes'
}
});
// Typical hierarchy with overrides
nconf
.overrides({ // Highest priority - always wins
NODE_ENV: 'production'
})
.argv() // Command-line args
.env() // Environment variables
.file('./config.json') // Configuration file
.defaults({ // Lowest priority fallbacks
port: 3000
});