0
# Configuration Options
1
2
Comprehensive options for controlling walkdir traversal behavior, performance optimization, and output formatting.
3
4
## Capabilities
5
6
### WalkOptions Interface
7
8
Complete configuration interface for all walkdir operations.
9
10
```javascript { .api }
11
/**
12
* Configuration options for walkdir operations
13
*/
14
interface WalkOptions {
15
/** Follow symbolic links during traversal (default: false) */
16
follow_symlinks?: boolean;
17
18
/** Only traverse one level deep, don't recurse into subdirectories */
19
no_recurse?: boolean;
20
21
/** Maximum traversal depth (emits 'maxdepth' event when reached) */
22
max_depth?: number;
23
24
/** Track inodes to prevent infinite loops (default: true) */
25
track_inodes?: boolean;
26
27
/** Make operation synchronous (equivalent to calling walkdir.sync) */
28
sync?: boolean;
29
30
/** Return {path: stat} object instead of path array */
31
return_object?: boolean;
32
33
/** Don't build internal result collection (memory optimization) */
34
no_return?: boolean;
35
36
/** Filter function for controlling which files/directories are processed */
37
filter?: (directory: string, files: string[]) => string[] | Promise<string[]>;
38
39
/** Custom fs implementation (e.g., graceful-fs) */
40
fs?: any;
41
42
/** Use lstat vs stat for link detection (default: true) */
43
find_links?: boolean;
44
}
45
```
46
47
### Symlink Handling
48
49
Control how symbolic links are processed during traversal.
50
51
```javascript { .api }
52
/**
53
* Symlink handling options
54
* @param {boolean} follow_symlinks - Whether to follow symbolic links (default: false)
55
* @param {boolean} find_links - Whether to detect symbolic links (default: true)
56
*/
57
```
58
59
**Usage Examples:**
60
61
```javascript
62
const walkdir = require('walkdir');
63
64
// Follow symbolic links (be careful of loops)
65
const paths = await walkdir.async('./project', {
66
follow_symlinks: true,
67
max_depth: 10 // Prevent infinite loops
68
});
69
70
// Detect but don't follow symlinks (default behavior)
71
const emitter = walkdir('./project', {
72
follow_symlinks: false, // explicit default
73
find_links: true // will emit 'link' events
74
});
75
76
emitter.on('link', (path, stat) => {
77
console.log('Found symlink:', path);
78
});
79
80
// Ignore symlinks entirely
81
const paths2 = walkdir.sync('./project', {
82
find_links: false // Use stat() instead of lstat(), won't detect links
83
});
84
```
85
86
### Depth Control
87
88
Options for controlling how deep the traversal goes.
89
90
```javascript { .api }
91
/**
92
* Depth control options
93
* @param {boolean} no_recurse - Only go one level deep
94
* @param {number} max_depth - Maximum depth to traverse
95
*/
96
```
97
98
**Usage Examples:**
99
100
```javascript
101
// Shallow traversal - only immediate children
102
const topLevel = walkdir.sync('./project', {
103
no_recurse: true
104
});
105
106
// Limited depth traversal
107
const limitedPaths = await walkdir.async('./project', {
108
max_depth: 3
109
});
110
111
// Handle depth limit reached
112
const emitter = walkdir('./deep-project', { max_depth: 5 });
113
emitter.on('maxdepth', (path, stat, depth) => {
114
console.log('Stopped at max depth:', depth, 'at path:', path);
115
});
116
117
// Combine with filtering for precise control
118
const controlledPaths = walkdir.sync('./project', {
119
max_depth: 4,
120
filter: (dir, files) => {
121
// Skip deep node_modules
122
if (dir.includes('node_modules')) return [];
123
return files;
124
}
125
});
126
```
127
128
### Performance Optimization
129
130
Options for optimizing memory usage and processing speed.
131
132
```javascript { .api }
133
/**
134
* Performance optimization options
135
* @param {boolean} no_return - Don't build internal result arrays/objects
136
* @param {boolean} track_inodes - Track inodes to prevent processing duplicates
137
* @param {object} fs - Custom fs implementation for better performance
138
*/
139
```
140
141
**Memory Optimization Examples:**
142
143
```javascript
144
// Process huge directories without memory buildup
145
let totalSize = 0;
146
let fileCount = 0;
147
148
walkdir.sync('/var/log', {
149
no_return: true // Don't store paths in memory
150
}, (path, stat) => {
151
if (stat.isFile()) {
152
fileCount++;
153
totalSize += stat.size;
154
}
155
});
156
157
console.log(`${fileCount} files, ${totalSize} bytes total`);
158
159
// Disable inode tracking for filesystems without unique inodes
160
const windowsPaths = walkdir.sync('C:\\Projects', {
161
track_inodes: false // Better for Windows/FAT32 filesystems
162
});
163
164
// Use graceful-fs for better performance and reliability
165
const gracefulFs = require('graceful-fs');
166
const paths = await walkdir.async('./project', {
167
fs: gracefulFs // Handles EMFILE/ENFILE errors better
168
});
169
```
170
171
### Output Format Control
172
173
Options for controlling the format of returned results.
174
175
```javascript { .api }
176
/**
177
* Output format options
178
* @param {boolean} return_object - Return {path: stat} instead of path array
179
* @param {boolean} no_return - Return nothing (for callback-only processing)
180
*/
181
```
182
183
**Format Examples:**
184
185
```javascript
186
// Default: array of paths
187
const pathArray = walkdir.sync('./project');
188
console.log('Paths:', pathArray);
189
190
// Object format: {path: stat}
191
const pathStats = walkdir.sync('./project', {
192
return_object: true
193
});
194
195
for (const [path, stat] of Object.entries(pathStats)) {
196
console.log(path, ':', stat.isDirectory() ? 'DIR' : 'FILE', stat.size);
197
}
198
199
// No return value, callback-only processing
200
walkdir.sync('./project', { no_return: true }, (path, stat) => {
201
// Process immediately, no memory storage
202
if (stat.isFile() && path.endsWith('.js')) {
203
analyzeJavaScriptFile(path);
204
}
205
});
206
207
// Async versions support the same formats
208
const asyncStats = await walkdir.async('./project', {
209
return_object: true
210
});
211
```
212
213
### Advanced Filtering
214
215
Sophisticated filtering capabilities including async filters.
216
217
```javascript { .api }
218
/**
219
* Filter function signature
220
* @param {string} directory - Current directory being read
221
* @param {string[]} files - Array of filenames in the directory
222
* @returns {string[]|Promise<string[]>} - Filtered array of filenames to process
223
*/
224
type FilterFunction = (directory: string, files: string[]) => string[] | Promise<string[]>;
225
```
226
227
**Filtering Examples:**
228
229
```javascript
230
// Simple synchronous filter
231
const jsFiles = walkdir.sync('./src', {
232
filter: (dir, files) => {
233
return files.filter(f => f.endsWith('.js') || f.endsWith('.ts'));
234
}
235
});
236
237
// Exclude directories and files
238
const filtered = walkdir.sync('./project', {
239
filter: (dir, files) => {
240
// Skip node_modules and .git directories entirely
241
if (dir.includes('node_modules') || dir.includes('.git')) {
242
return [];
243
}
244
245
// Only include source files
246
return files.filter(f => {
247
return f.endsWith('.js') || f.endsWith('.ts') || f.endsWith('.json');
248
});
249
}
250
});
251
252
// Async filter with file system checks
253
const validFiles = await walkdir.async('./uploads', {
254
filter: async (dir, files) => {
255
const results = [];
256
257
for (const file of files) {
258
const fullPath = path.join(dir, file);
259
try {
260
const stat = await fs.promises.stat(fullPath);
261
// Only include files smaller than 10MB
262
if (stat.isFile() && stat.size < 10 * 1024 * 1024) {
263
results.push(file);
264
}
265
} catch (error) {
266
// Skip files we can't stat
267
}
268
}
269
270
return results;
271
}
272
});
273
274
// Pattern-based filtering
275
const matchedFiles = walkdir.sync('./docs', {
276
filter: (dir, files) => {
277
return files.filter(f => {
278
// Include markdown files and directories
279
return f.endsWith('.md') || !f.includes('.');
280
});
281
}
282
});
283
```
284
285
### Custom File System Implementation
286
287
Use alternative fs implementations for enhanced functionality.
288
289
```javascript { .api }
290
/**
291
* Custom fs implementation option
292
* @param {object} fs - Object with fs methods: stat, lstat, readdir, readlink (and sync versions)
293
*/
294
```
295
296
**Custom FS Examples:**
297
298
```javascript
299
const gracefulFs = require('graceful-fs');
300
const mockFs = require('mock-fs');
301
302
// Use graceful-fs for better error handling
303
const robustPaths = await walkdir.async('./project', {
304
fs: gracefulFs // Handles EMFILE errors, retries failed operations
305
});
306
307
// Use mock-fs for testing
308
mockFs({
309
'/fake-dir': {
310
'file1.txt': 'content',
311
'subdir': {
312
'file2.js': 'console.log("test");'
313
}
314
}
315
});
316
317
const mockPaths = walkdir.sync('/fake-dir', {
318
fs: mockFs // Uses mocked filesystem
319
});
320
321
mockFs.restore();
322
323
// Custom fs wrapper with logging
324
const loggingFs = {
325
...require('fs'),
326
readdir: (path, callback) => {
327
console.log('Reading directory:', path);
328
return require('fs').readdir(path, callback);
329
},
330
readdirSync: (path) => {
331
console.log('Reading directory sync:', path);
332
return require('fs').readdirSync(path);
333
}
334
};
335
336
const loggedPaths = walkdir.sync('./project', {
337
fs: loggingFs // Logs all directory reads
338
});
339
```
340
341
### Option Combinations
342
343
Common combinations of options for specific use cases.
344
345
```javascript
346
// High-performance large directory scan
347
const bigScan = await walkdir.async('/huge/directory', {
348
no_return: true, // Don't store results in memory
349
track_inodes: false, // Skip inode tracking overhead
350
fs: gracefulFs // Better error handling
351
}, (path, stat) => {
352
// Process each path immediately
353
processPath(path, stat);
354
});
355
356
// Safe symlink following with depth protection
357
const safePaths = await walkdir.async('./project', {
358
follow_symlinks: true,
359
max_depth: 8,
360
track_inodes: true // Prevent loops
361
});
362
363
// Fast shallow scan with filtering
364
const quickScan = walkdir.sync('./src', {
365
no_recurse: true, // Only top level
366
return_object: true, // Get stat info
367
filter: (dir, files) => files.filter(f => !f.startsWith('.'))
368
});
369
```