0
# Promise-based Operations
1
2
Modern async/await compatible interface that returns promises for directory traversal operations.
3
4
## Capabilities
5
6
### Async Function
7
8
Walk directory tree and return a promise that resolves with all discovered paths.
9
10
```javascript { .api }
11
/**
12
* Walk directory tree and return promise of results
13
* @param {string} path - Directory path to walk
14
* @param {WalkOptions} [options] - Walk configuration options
15
* @param {WalkEventListener} [eventListener] - Optional callback for each path found
16
* @returns {Promise<string[]|Object<string,fs.Stats>>} - Promise resolving to paths array or stats object
17
*/
18
function walkdir.async(path, options, eventListener);
19
```
20
21
**Promise Resolution:**
22
- **Default**: Resolves to `string[]` - Array of all discovered paths
23
- **With `return_object: true`**: Resolves to `{[path]: fs.Stats}` - Object with paths as keys and stat objects as values
24
- **With `no_return: true`**: Resolves to `undefined` after completion
25
26
**Usage Examples:**
27
28
```javascript
29
const walkdir = require('walkdir');
30
31
// Basic async/await usage
32
async function listFiles() {
33
try {
34
const paths = await walkdir.async('./my-directory');
35
console.log('Found', paths.length, 'items');
36
return paths;
37
} catch (error) {
38
console.error('Failed to walk directory:', error);
39
}
40
}
41
42
// Promise chain syntax
43
walkdir.async('./src')
44
.then(paths => {
45
const jsFiles = paths.filter(p => p.endsWith('.js'));
46
console.log('JavaScript files:', jsFiles);
47
})
48
.catch(error => {
49
console.error('Walk failed:', error);
50
});
51
52
// With event listener callback
53
const paths = await walkdir.async('./project', (path, stat) => {
54
if (stat.isFile() && stat.size > 1024 * 1024) {
55
console.log('Large file found:', path);
56
}
57
});
58
59
// Return object format
60
const stats = await walkdir.async('./project', { return_object: true });
61
for (const [path, stat] of Object.entries(stats)) {
62
console.log(path, 'modified:', stat.mtime);
63
}
64
```
65
66
### Async with Options
67
68
Configure async behavior with comprehensive options.
69
70
```javascript { .api }
71
/**
72
* Walk directory tree with specific options and return promise
73
* @param {string} path - Directory path to walk
74
* @param {WalkOptions} options - Configuration options
75
* @param {WalkEventListener} [eventListener] - Optional callback for each path
76
* @returns {Promise<string[]|Object<string,fs.Stats>|undefined>} - Promise resolving based on options
77
*/
78
function walkdir.async(path, options, eventListener);
79
```
80
81
**Advanced Usage Examples:**
82
83
```javascript
84
// Depth-limited traversal
85
const shallowPaths = await walkdir.async('./deep-directory', {
86
max_depth: 3
87
});
88
89
// Custom filtering with promise-based filter
90
const filteredPaths = await walkdir.async('./src', {
91
filter: async (dir, files) => {
92
// Async filter - could involve file system checks, database lookups, etc.
93
const results = [];
94
for (const file of files) {
95
if (file.endsWith('.js') || file.endsWith('.ts')) {
96
results.push(file);
97
}
98
}
99
return results;
100
}
101
});
102
103
// Memory-optimized async traversal
104
await walkdir.async('/var/log', { no_return: true }, (path, stat) => {
105
// Process each path immediately without building result array
106
if (stat.isFile() && path.endsWith('.log')) {
107
console.log('Log file:', path, 'Size:', stat.size);
108
}
109
});
110
111
// Follow symlinks
112
const allPaths = await walkdir.async('./project', {
113
follow_symlinks: true,
114
max_depth: 10 // Prevent infinite loops
115
});
116
117
// Custom fs implementation
118
const gracefulFs = require('graceful-fs');
119
const paths = await walkdir.async('./directory', {
120
fs: gracefulFs // Use graceful-fs for better error handling
121
});
122
```
123
124
### Promise Error Handling
125
126
The async function provides detailed error handling through promise rejection.
127
128
```javascript { .api }
129
/**
130
* Promise rejection scenarios:
131
* - Target directory doesn't exist or can't be accessed
132
* - Permissions error on initial path
133
* - Filter function throws an error
134
* - Custom fs implementation throws an error
135
*/
136
```
137
138
**Error Handling Examples:**
139
140
```javascript
141
try {
142
const paths = await walkdir.async('./nonexistent');
143
} catch (error) {
144
console.error('Directory access failed:', error.message);
145
// Error includes details about the failing path
146
}
147
148
// Handle nested path failures gracefully
149
const paths = await walkdir.async('./mixed-permissions', (path, stat) => {
150
console.log('Accessible path:', path);
151
});
152
// Note: nested permission errors don't cause promise rejection
153
// They're handled by emitting 'fail' events internally
154
155
// Monitor for nested failures with event listener
156
const emitter = walkdir('./mixed-permissions');
157
emitter.on('fail', (path, error) => {
158
console.warn('Could not access:', path, error.message);
159
});
160
161
const paths = await walkdir.async('./mixed-permissions');
162
```
163
164
### Combining with Event Listeners
165
166
The async function can be combined with event listeners for real-time processing.
167
168
```javascript
169
async function processLargeDirectory() {
170
let processedCount = 0;
171
172
const paths = await walkdir.async('./huge-directory', (path, stat) => {
173
processedCount++;
174
if (processedCount % 1000 === 0) {
175
console.log(`Processed ${processedCount} items so far...`);
176
}
177
178
// Real-time processing
179
if (stat.isFile() && path.endsWith('.txt')) {
180
// Process text files immediately
181
processFile(path);
182
}
183
});
184
185
console.log(`Completed! Total items: ${paths.length}`);
186
return paths;
187
}
188
```
189
190
## Integration Patterns
191
192
### With Modern async/await
193
194
```javascript
195
async function analyzeProject(projectPath) {
196
const [allPaths, stats] = await Promise.all([
197
walkdir.async(projectPath),
198
walkdir.async(projectPath, { return_object: true })
199
]);
200
201
return {
202
totalFiles: allPaths.length,
203
totalSize: Object.values(stats)
204
.filter(stat => stat.isFile())
205
.reduce((sum, stat) => sum + stat.size, 0),
206
directories: Object.values(stats)
207
.filter(stat => stat.isDirectory()).length
208
};
209
}
210
```
211
212
### Error Recovery Patterns
213
214
```javascript
215
async function robustWalk(path, options = {}) {
216
const maxRetries = 3;
217
let attempt = 0;
218
219
while (attempt < maxRetries) {
220
try {
221
return await walkdir.async(path, options);
222
} catch (error) {
223
attempt++;
224
if (attempt >= maxRetries) throw error;
225
226
console.warn(`Walk attempt ${attempt} failed, retrying...`);
227
await new Promise(resolve => setTimeout(resolve, 1000));
228
}
229
}
230
}
231
```