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
File-based configuration with support for JSON and INI formats, encrypted storage, and automatic file discovery with search functionality. File operations provide both synchronous and asynchronous access patterns.
Add a file-based configuration store to the hierarchy with flexible path and format options.
/**
* Add file store to configuration hierarchy
* @param {string|Object} key - Store name, file path, or options object
* @param {string|Object} [options] - File path or options object
* @returns {Provider} Provider instance for chaining
*/
file(key, options);Usage Examples:
const nconf = require('nconf');
// Simple file path
nconf.file('./config.json');
// Named file store
nconf.file('config', './config.json');
// Full options object
nconf.file({
file: './config.json',
dir: './config',
search: true
});
// Named store with options
nconf.file('userconfig', {
file: '.myapprc',
dir: process.env.HOME,
search: true,
format: nconf.formats.ini
});
// Multiple file stores with priority
nconf
.file('local', './config/local.json')
.file('environment', `./config/${process.env.NODE_ENV}.json`)
.file('default', './config/default.json');Load configuration data from all configured stores with hierarchical merging.
/**
* Load configuration from all stores
* @param {function} [callback] - Optional callback for async operation
* @returns {Object|undefined} Configuration object (sync) or undefined (async)
*/
load(callback);Usage Examples:
// Synchronous load
const config = nconf.load();
console.log('Loaded config:', config);
// Asynchronous load
nconf.load((err, config) => {
if (err) {
console.error('Failed to load configuration:', err);
return;
}
console.log('Configuration loaded:', config);
startApplication(config);
});
// Load after store setup
nconf
.file('./config.json')
.env()
.load((err, config) => {
if (err) throw err;
// Config now contains merged data from file and environment
});Save configuration data to all writable stores with format-specific serialization.
/**
* Save configuration to all stores
* @param {*} [value] - Optional specific value to save
* @param {function} [callback] - Optional callback for async operation
* @returns {Object|undefined} Saved configuration data (sync) or undefined (async)
*/
save(value, callback);Usage Examples:
// Synchronous save
nconf.set('app:version', '2.0.0');
const saved = nconf.save();
console.log('Saved configuration:', saved);
// Asynchronous save
nconf.save((err, data) => {
if (err) {
console.error('Failed to save configuration:', err);
return;
}
console.log('Configuration saved successfully:', data);
});
// Save specific value
nconf.save({ timestamp: Date.now() }, (err) => {
if (err) console.error('Save failed:', err);
else console.log('Timestamp saved');
});Automatic file discovery by searching up the directory tree from a base directory.
/**
* Search for configuration file up the directory tree
* @param {string} [base] - Base directory to start search (default: process.cwd())
* @returns {string|false} Found file path or false if not found
*/
search(base);Usage Examples:
// File store with search enabled
nconf.file({
file: '.myapprc',
search: true // Searches up from current directory
});
// File store with custom search base
nconf.file({
file: 'config.json',
dir: '/opt/myapp',
search: true // Searches up from /opt/myapp
});
// Manual search
const configFile = nconf.stores.config.search('/home/user/projects/myapp');
if (configFile) {
console.log('Found config at:', configFile);
}Support for multiple configuration file formats with extensible parsing.
/**
* Available file formats
*/
const formats = {
json: {
parse: Function, // JSON.parse
stringify: Function // JSON.stringify with pretty printing
},
ini: {
parse: Function, // INI format parser
stringify: Function // INI format stringifier
}
};Usage Examples:
// JSON format (default)
nconf.file('./config.json');
// INI format
nconf.file({
file: './config.ini',
format: nconf.formats.ini
});
// Custom format
const yamlFormat = {
parse: require('js-yaml').load,
stringify: require('js-yaml').dump
};
nconf.file({
file: './config.yaml',
format: yamlFormat
});
// Format-specific options
nconf.file({
file: './config.json',
format: nconf.formats.json,
spacing: 4, // 4-space indentation
json_spacing: 4 // Alternative to spacing (same functionality)
});Secure configuration storage with AES encryption support for sensitive data.
/**
* Encryption options for secure file storage
*/
interface SecureOptions {
secret: string; // Encryption secret key
alg?: string; // Encryption algorithm (default: 'aes-256-ctr')
secretPath?: string; // Path to file containing secret
}Usage Examples:
// Basic encryption with secret
nconf.file({
file: './secure-config.json',
secure: {
secret: process.env.CONFIG_SECRET
}
});
// Custom encryption algorithm
nconf.file({
file: './config.enc',
secure: {
secret: 'my-secret-key',
alg: 'aes-192-cbc'
}
});
// Secret from file
nconf.file({
file: './production.json',
secure: {
secretPath: '/etc/myapp/secret.key'
}
});
// Buffer or string secret
const secretBuffer = Buffer.from('my-secret', 'utf8');
nconf.file({
file: './config.json',
secure: { secret: secretBuffer }
});Direct file store operations for advanced usage scenarios.
/**
* Save to specific file path
* @param {string} path - Target file path
* @param {Object} [format] - Format parser (default: store format)
* @param {function} [callback] - Optional callback
*/
saveToFile(path, format, callback);
/**
* Synchronous save to current file
* @returns {Object} Saved configuration data
*/
saveSync();
/**
* Synchronous load from current file
* @returns {Object} Loaded configuration data
*/
loadSync();
/**
* Parse file contents with format and decryption
* @param {string} contents - File contents to parse
* @returns {Object} Parsed configuration object
*/
parse(contents);
/**
* Stringify configuration with format and encryption
* @param {Object} [format] - Format parser (default: store format)
* @returns {string} Stringified configuration
*/
stringify(format);Usage Examples:
// Direct file operations
const fileStore = nconf.stores.config;
// Save to alternate location
fileStore.saveToFile('./backup.json', (err) => {
if (err) console.error('Backup failed:', err);
else console.log('Configuration backed up');
});
// Synchronous operations
try {
const data = fileStore.loadSync();
console.log('Loaded data:', data);
fileStore.saveSync();
console.log('Data saved synchronously');
} catch (err) {
console.error('File operation failed:', err);
}
// Custom parsing/stringifying
const rawContent = fs.readFileSync('config.json', 'utf8');
const parsed = fileStore.parse(rawContent);
const stringified = fileStore.stringify(nconf.formats.json);File operations can throw or return errors for various conditions:
file option// Robust error handling
nconf.file({
file: './config.json'
});
nconf.load((err, config) => {
if (err) {
if (err.message.includes('ENOENT')) {
console.log('Config file not found, using defaults');
return;
}
if (err.message.includes('Error parsing')) {
console.error('Invalid JSON in config file:', err.message);
process.exit(1);
}
console.error('Configuration load error:', err);
process.exit(1);
}
// Configuration loaded successfully
console.log('Configuration ready');
});