0
# Configuration Management
1
2
Core configuration operations providing hierarchical access to configuration data with support for nested keys, multiple data sources, and both synchronous and asynchronous operations.
3
4
## Capabilities
5
6
### Get Configuration
7
8
Retrieve configuration values with hierarchical lookup across all configured stores in priority order.
9
10
```javascript { .api }
11
/**
12
* Retrieve configuration value for the specified key
13
* @param {string|function} [key] - Configuration key (supports nested keys with ':' delimiter), or callback for full config
14
* @param {function} [callback] - Optional callback for async operation
15
* @returns {*} Configuration value or undefined if not found
16
*/
17
get(key, callback);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const nconf = require('nconf');
24
25
// Synchronous get
26
const dbHost = nconf.get('database:host');
27
const port = nconf.get('server:port');
28
const config = nconf.get('database'); // Gets entire nested object
29
30
// Get root configuration
31
const allConfig = nconf.get();
32
33
// Asynchronous get
34
nconf.get('database:host', (err, value) => {
35
if (err) console.error('Error:', err);
36
else console.log('Database host:', value);
37
});
38
39
// Get with nested object merging across stores
40
nconf.get('database', (err, dbConfig) => {
41
// Merges database config from all stores
42
console.log(dbConfig); // { host: 'localhost', port: 5432, ssl: true }
43
});
44
```
45
46
### Set Configuration
47
48
Set configuration values with automatic nested object creation and hierarchical key support.
49
50
```javascript { .api }
51
/**
52
* Set configuration value for the specified key
53
* @param {string} key - Configuration key (supports nested keys with ':' delimiter)
54
* @param {*} value - Value to set (can be primitive, object, or array)
55
* @param {function} [callback] - Optional callback for async operation
56
* @returns {Provider} Provider instance for chaining
57
*/
58
set(key, value, callback);
59
```
60
61
**Usage Examples:**
62
63
```javascript
64
// Set simple values
65
nconf.set('app:name', 'MyApp');
66
nconf.set('app:version', '1.0.0');
67
68
// Set nested objects
69
nconf.set('database', {
70
host: 'localhost',
71
port: 5432,
72
ssl: true
73
});
74
75
// Set array values
76
nconf.set('app:features', ['auth', 'logging', 'metrics']);
77
78
// Chaining operations
79
nconf
80
.set('app:env', 'production')
81
.set('app:debug', false)
82
.set('app:timeout', 30000);
83
84
// Asynchronous set
85
nconf.set('cache:ttl', 3600, (err) => {
86
if (err) console.error('Error setting cache TTL:', err);
87
else console.log('Cache TTL set successfully');
88
});
89
```
90
91
### Clear Configuration
92
93
Remove configuration keys and their values from all writable stores.
94
95
```javascript { .api }
96
/**
97
* Remove configuration key and its value
98
* @param {string} key - Configuration key to remove
99
* @param {function} [callback] - Optional callback for async operation
100
* @returns {Provider} Provider instance for chaining
101
*/
102
clear(key, callback);
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
// Clear specific key
109
nconf.clear('database:password');
110
111
// Clear nested object
112
nconf.clear('temp:cache');
113
114
// Asynchronous clear
115
nconf.clear('session:tokens', (err) => {
116
if (err) console.error('Error clearing tokens:', err);
117
else console.log('Session tokens cleared');
118
});
119
```
120
121
### Merge Configuration
122
123
Merge objects into existing configuration with deep merging support and automatic nested key creation.
124
125
```javascript { .api }
126
/**
127
* Merge object into existing configuration
128
* @param {string} [key] - Target key to merge into, or merge into root if not provided
129
* @param {Object} value - Object to merge (must be an object)
130
* @param {function} [callback] - Optional callback for async operation
131
* @returns {Provider} Provider instance for chaining
132
*/
133
merge(key, value, callback);
134
```
135
136
**Usage Examples:**
137
138
```javascript
139
// Merge into specific key
140
nconf.merge('database', {
141
pool: { min: 2, max: 10 },
142
timeout: 5000
143
});
144
145
// Merge into root (two-parameter form)
146
nconf.merge({
147
app: { name: 'MyApp' },
148
server: { host: '0.0.0.0' }
149
});
150
151
// Merge with callback
152
nconf.merge('api:settings', {
153
rateLimit: 1000,
154
timeout: 30000
155
}, (err) => {
156
if (err) console.error('Merge failed:', err);
157
else console.log('API settings merged successfully');
158
});
159
160
// Deep merging behavior
161
nconf.set('existing', { a: 1, b: { x: 10 } });
162
nconf.merge('existing', { b: { y: 20 }, c: 3 });
163
// Result: { a: 1, b: { x: 10, y: 20 }, c: 3 }
164
```
165
166
### Any Configuration
167
168
Get the first truthy value from a list of configuration keys, useful for fallback scenarios.
169
170
```javascript { .api }
171
/**
172
* Get first truthy value from a list of keys
173
* @param {string[]|...string} keys - Array of keys or variable arguments
174
* @param {function} [callback] - Optional callback for async operation
175
* @returns {*} First truthy value found or null if none found
176
*/
177
any(keys, callback);
178
```
179
180
**Usage Examples:**
181
182
```javascript
183
// Array form
184
const host = nconf.any(['DB_HOST', 'DATABASE_HOST', 'db:host']);
185
186
// Variable arguments form
187
const port = nconf.any('DB_PORT', 'DATABASE_PORT', 'db:port', 'DEFAULT_PORT');
188
189
// With default fallback
190
const timeout = nconf.any(['API_TIMEOUT', 'app:timeout']) || 5000;
191
192
// Asynchronous form
193
nconf.any(['redis:url', 'REDIS_URL', 'cache:redis'], (err, value) => {
194
if (err) console.error('Error finding Redis URL:', err);
195
else console.log('Redis URL:', value || 'not found');
196
});
197
```
198
199
### Required Configuration
200
201
Validate that required configuration keys are present, throwing an error if any are missing.
202
203
```javascript { .api }
204
/**
205
* Validate that required configuration keys are present
206
* @param {string[]} keys - Array of required key names
207
* @throws {Error} Throws error with missing key names if validation fails
208
* @returns {boolean} Returns true if all keys are present
209
*/
210
required(keys);
211
```
212
213
**Usage Examples:**
214
215
```javascript
216
// Validate required keys
217
try {
218
nconf.required(['database:host', 'database:port', 'app:secret']);
219
console.log('All required configuration present');
220
} catch (err) {
221
console.error('Missing required configuration:', err.message);
222
process.exit(1);
223
}
224
225
// In application startup
226
const requiredKeys = [
227
'DATABASE_URL',
228
'JWT_SECRET',
229
'API_KEY',
230
'app:name'
231
];
232
233
if (nconf.required(requiredKeys)) {
234
// Safe to start application
235
startServer();
236
}
237
```
238
239
### Reset Configuration
240
241
Clear all configuration data from all writable stores.
242
243
```javascript { .api }
244
/**
245
* Clear all configuration data
246
* @param {function} [callback] - Optional callback for async operation
247
* @returns {Provider} Provider instance for chaining
248
*/
249
reset(callback);
250
```
251
252
**Usage Examples:**
253
254
```javascript
255
// Synchronous reset
256
nconf.reset();
257
258
// Asynchronous reset
259
nconf.reset((err) => {
260
if (err) console.error('Error resetting configuration:', err);
261
else console.log('Configuration reset successfully');
262
});
263
264
// Reset and reload
265
nconf.reset().load((err) => {
266
if (err) console.error('Error reloading after reset:', err);
267
else console.log('Configuration reset and reloaded');
268
});
269
```
270
271
### Default Values
272
273
Add a literal store containing default configuration values with lowest priority in the hierarchy.
274
275
```javascript { .api }
276
/**
277
* Add default configuration values (lowest priority store)
278
* @param {Object} options - Default configuration object or store options
279
* @returns {Provider} Provider instance for chaining
280
*/
281
defaults(options);
282
```
283
284
**Usage Examples:**
285
286
```javascript
287
// Add default values
288
nconf.defaults({
289
app: {
290
name: 'MyApp',
291
version: '1.0.0',
292
debug: false,
293
port: 3000
294
},
295
database: {
296
host: 'localhost',
297
port: 5432,
298
timeout: 30000
299
}
300
});
301
302
// With store options
303
nconf.defaults({
304
type: 'literal',
305
store: {
306
server: { host: '127.0.0.1', port: 8080 },
307
cache: { enabled: true, ttl: 300 }
308
}
309
});
310
311
// Chaining with hierarchy
312
nconf
313
.argv() // Highest priority
314
.env() // Second priority
315
.file('./config.json') // Third priority
316
.defaults({ // Lowest priority
317
env: 'development',
318
debug: true
319
});
320
```
321
322
### Override Values
323
324
Add a literal store containing override configuration values with highest priority in the hierarchy.
325
326
```javascript { .api }
327
/**
328
* Add override configuration values (highest priority store)
329
* @param {Object} options - Override configuration object or store options
330
* @returns {Provider} Provider instance for chaining
331
*/
332
overrides(options);
333
```
334
335
**Usage Examples:**
336
337
```javascript
338
// Add override values (always take precedence)
339
nconf.overrides({
340
app: {
341
env: 'production', // Always production regardless of other sources
342
debug: false // Always disable debug in production
343
},
344
security: {
345
enabled: true // Security always enabled
346
}
347
});
348
349
// With store options
350
nconf.overrides({
351
type: 'literal',
352
store: {
353
'always': 'this value',
354
'never': 'changes'
355
}
356
});
357
358
// Typical hierarchy with overrides
359
nconf
360
.overrides({ // Highest priority - always wins
361
NODE_ENV: 'production'
362
})
363
.argv() // Command-line args
364
.env() // Environment variables
365
.file('./config.json') // Configuration file
366
.defaults({ // Lowest priority fallbacks
367
port: 3000
368
});
369
```