0
# File Operations
1
2
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.
3
4
## Capabilities
5
6
### File Store
7
8
Add a file-based configuration store to the hierarchy with flexible path and format options.
9
10
```javascript { .api }
11
/**
12
* Add file store to configuration hierarchy
13
* @param {string|Object} key - Store name, file path, or options object
14
* @param {string|Object} [options] - File path or options object
15
* @returns {Provider} Provider instance for chaining
16
*/
17
file(key, options);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const nconf = require('nconf');
24
25
// Simple file path
26
nconf.file('./config.json');
27
28
// Named file store
29
nconf.file('config', './config.json');
30
31
// Full options object
32
nconf.file({
33
file: './config.json',
34
dir: './config',
35
search: true
36
});
37
38
// Named store with options
39
nconf.file('userconfig', {
40
file: '.myapprc',
41
dir: process.env.HOME,
42
search: true,
43
format: nconf.formats.ini
44
});
45
46
// Multiple file stores with priority
47
nconf
48
.file('local', './config/local.json')
49
.file('environment', `./config/${process.env.NODE_ENV}.json`)
50
.file('default', './config/default.json');
51
```
52
53
### Load Configuration
54
55
Load configuration data from all configured stores with hierarchical merging.
56
57
```javascript { .api }
58
/**
59
* Load configuration from all stores
60
* @param {function} [callback] - Optional callback for async operation
61
* @returns {Object|undefined} Configuration object (sync) or undefined (async)
62
*/
63
load(callback);
64
```
65
66
**Usage Examples:**
67
68
```javascript
69
// Synchronous load
70
const config = nconf.load();
71
console.log('Loaded config:', config);
72
73
// Asynchronous load
74
nconf.load((err, config) => {
75
if (err) {
76
console.error('Failed to load configuration:', err);
77
return;
78
}
79
console.log('Configuration loaded:', config);
80
startApplication(config);
81
});
82
83
// Load after store setup
84
nconf
85
.file('./config.json')
86
.env()
87
.load((err, config) => {
88
if (err) throw err;
89
// Config now contains merged data from file and environment
90
});
91
```
92
93
### Save Configuration
94
95
Save configuration data to all writable stores with format-specific serialization.
96
97
```javascript { .api }
98
/**
99
* Save configuration to all stores
100
* @param {*} [value] - Optional specific value to save
101
* @param {function} [callback] - Optional callback for async operation
102
* @returns {Object|undefined} Saved configuration data (sync) or undefined (async)
103
*/
104
save(value, callback);
105
```
106
107
**Usage Examples:**
108
109
```javascript
110
// Synchronous save
111
nconf.set('app:version', '2.0.0');
112
const saved = nconf.save();
113
console.log('Saved configuration:', saved);
114
115
// Asynchronous save
116
nconf.save((err, data) => {
117
if (err) {
118
console.error('Failed to save configuration:', err);
119
return;
120
}
121
console.log('Configuration saved successfully:', data);
122
});
123
124
// Save specific value
125
nconf.save({ timestamp: Date.now() }, (err) => {
126
if (err) console.error('Save failed:', err);
127
else console.log('Timestamp saved');
128
});
129
```
130
131
## File Store Features
132
133
### File Search
134
135
Automatic file discovery by searching up the directory tree from a base directory.
136
137
```javascript { .api }
138
/**
139
* Search for configuration file up the directory tree
140
* @param {string} [base] - Base directory to start search (default: process.cwd())
141
* @returns {string|false} Found file path or false if not found
142
*/
143
search(base);
144
```
145
146
**Usage Examples:**
147
148
```javascript
149
// File store with search enabled
150
nconf.file({
151
file: '.myapprc',
152
search: true // Searches up from current directory
153
});
154
155
// File store with custom search base
156
nconf.file({
157
file: 'config.json',
158
dir: '/opt/myapp',
159
search: true // Searches up from /opt/myapp
160
});
161
162
// Manual search
163
const configFile = nconf.stores.config.search('/home/user/projects/myapp');
164
if (configFile) {
165
console.log('Found config at:', configFile);
166
}
167
```
168
169
### File Formats
170
171
Support for multiple configuration file formats with extensible parsing.
172
173
```javascript { .api }
174
/**
175
* Available file formats
176
*/
177
const formats = {
178
json: {
179
parse: Function, // JSON.parse
180
stringify: Function // JSON.stringify with pretty printing
181
},
182
ini: {
183
parse: Function, // INI format parser
184
stringify: Function // INI format stringifier
185
}
186
};
187
```
188
189
**Usage Examples:**
190
191
```javascript
192
// JSON format (default)
193
nconf.file('./config.json');
194
195
// INI format
196
nconf.file({
197
file: './config.ini',
198
format: nconf.formats.ini
199
});
200
201
// Custom format
202
const yamlFormat = {
203
parse: require('js-yaml').load,
204
stringify: require('js-yaml').dump
205
};
206
207
nconf.file({
208
file: './config.yaml',
209
format: yamlFormat
210
});
211
212
// Format-specific options
213
nconf.file({
214
file: './config.json',
215
format: nconf.formats.json,
216
spacing: 4, // 4-space indentation
217
json_spacing: 4 // Alternative to spacing (same functionality)
218
});
219
```
220
221
### Encrypted Files
222
223
Secure configuration storage with AES encryption support for sensitive data.
224
225
```javascript { .api }
226
/**
227
* Encryption options for secure file storage
228
*/
229
interface SecureOptions {
230
secret: string; // Encryption secret key
231
alg?: string; // Encryption algorithm (default: 'aes-256-ctr')
232
secretPath?: string; // Path to file containing secret
233
}
234
```
235
236
**Usage Examples:**
237
238
```javascript
239
// Basic encryption with secret
240
nconf.file({
241
file: './secure-config.json',
242
secure: {
243
secret: process.env.CONFIG_SECRET
244
}
245
});
246
247
// Custom encryption algorithm
248
nconf.file({
249
file: './config.enc',
250
secure: {
251
secret: 'my-secret-key',
252
alg: 'aes-192-cbc'
253
}
254
});
255
256
// Secret from file
257
nconf.file({
258
file: './production.json',
259
secure: {
260
secretPath: '/etc/myapp/secret.key'
261
}
262
});
263
264
// Buffer or string secret
265
const secretBuffer = Buffer.from('my-secret', 'utf8');
266
nconf.file({
267
file: './config.json',
268
secure: { secret: secretBuffer }
269
});
270
```
271
272
### File Store Methods
273
274
Direct file store operations for advanced usage scenarios.
275
276
```javascript { .api }
277
/**
278
* Save to specific file path
279
* @param {string} path - Target file path
280
* @param {Object} [format] - Format parser (default: store format)
281
* @param {function} [callback] - Optional callback
282
*/
283
saveToFile(path, format, callback);
284
285
/**
286
* Synchronous save to current file
287
* @returns {Object} Saved configuration data
288
*/
289
saveSync();
290
291
/**
292
* Synchronous load from current file
293
* @returns {Object} Loaded configuration data
294
*/
295
loadSync();
296
297
/**
298
* Parse file contents with format and decryption
299
* @param {string} contents - File contents to parse
300
* @returns {Object} Parsed configuration object
301
*/
302
parse(contents);
303
304
/**
305
* Stringify configuration with format and encryption
306
* @param {Object} [format] - Format parser (default: store format)
307
* @returns {string} Stringified configuration
308
*/
309
stringify(format);
310
```
311
312
**Usage Examples:**
313
314
```javascript
315
// Direct file operations
316
const fileStore = nconf.stores.config;
317
318
// Save to alternate location
319
fileStore.saveToFile('./backup.json', (err) => {
320
if (err) console.error('Backup failed:', err);
321
else console.log('Configuration backed up');
322
});
323
324
// Synchronous operations
325
try {
326
const data = fileStore.loadSync();
327
console.log('Loaded data:', data);
328
329
fileStore.saveSync();
330
console.log('Data saved synchronously');
331
} catch (err) {
332
console.error('File operation failed:', err);
333
}
334
335
// Custom parsing/stringifying
336
const rawContent = fs.readFileSync('config.json', 'utf8');
337
const parsed = fileStore.parse(rawContent);
338
const stringified = fileStore.stringify(nconf.formats.json);
339
```
340
341
## Error Handling
342
343
File operations can throw or return errors for various conditions:
344
345
- **Missing file option**: File store requires a `file` option
346
- **Parse errors**: Invalid JSON/INI format or corrupted encrypted files
347
- **Permission errors**: File system access restrictions
348
- **Encryption errors**: Invalid secrets or corrupted encrypted data
349
- **Path errors**: Invalid file paths or directory traversal issues
350
351
```javascript
352
// Robust error handling
353
nconf.file({
354
file: './config.json'
355
});
356
357
nconf.load((err, config) => {
358
if (err) {
359
if (err.message.includes('ENOENT')) {
360
console.log('Config file not found, using defaults');
361
return;
362
}
363
if (err.message.includes('Error parsing')) {
364
console.error('Invalid JSON in config file:', err.message);
365
process.exit(1);
366
}
367
console.error('Configuration load error:', err);
368
process.exit(1);
369
}
370
371
// Configuration loaded successfully
372
console.log('Configuration ready');
373
});
374
```