0
# Synchronous Operations
1
2
Synchronous directory traversal that blocks execution until all paths are discovered and returned as a complete result set.
3
4
## Capabilities
5
6
### Sync Function
7
8
Synchronously walk a directory tree and return all results immediately.
9
10
```javascript { .api }
11
/**
12
* Synchronously walk directory tree and return all paths
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 {string[]|Object<string,fs.Stats>} - Array of paths or object mapping paths to stats
17
*/
18
function walkdir.sync(path, options, eventListener);
19
```
20
21
**Return Types:**
22
- **Default**: `string[]` - Array of all discovered paths
23
- **With `return_object: true`**: `{[path]: fs.Stats}` - Object with paths as keys and stat objects as values
24
25
**Usage Examples:**
26
27
```javascript
28
const walkdir = require('walkdir');
29
30
// Basic sync - returns array of paths
31
const paths = walkdir.sync('./my-directory');
32
console.log('Found', paths.length, 'items');
33
paths.forEach(path => console.log(path));
34
35
// Sync with callback - still returns array, but calls function for each path
36
const paths2 = walkdir.sync('./my-directory', (path, stat) => {
37
if (stat.isFile()) {
38
console.log('File:', path, 'Size:', stat.size);
39
}
40
});
41
42
// Sync with options - return object format
43
const stats = walkdir.sync('./my-directory', { return_object: true });
44
for (const [path, stat] of Object.entries(stats)) {
45
console.log(path, {
46
type: stat.isDirectory() ? 'dir' : 'file',
47
size: stat.size,
48
modified: stat.mtime
49
});
50
}
51
52
// Sync with depth limit
53
const shallowPaths = walkdir.sync('./my-directory', { max_depth: 2 });
54
console.log('Paths within 2 levels:', shallowPaths);
55
56
// Sync with filtering
57
const jsFiles = walkdir.sync('./src', {
58
filter: (dir, files) => files.filter(f => f.endsWith('.js'))
59
});
60
61
// Memory-optimized sync (no return array built)
62
walkdir.sync('./huge-directory', { no_return: true }, (path, stat) => {
63
// Process each path immediately - no memory buildup
64
if (stat.isFile() && stat.size > 1024 * 1024) {
65
console.log('Large file:', path, stat.size);
66
}
67
});
68
```
69
70
### Sync with Return Object
71
72
When `return_object: true` is specified, the sync function returns an object instead of an array.
73
74
```javascript { .api }
75
/**
76
* Synchronously walk directory with object return format
77
* @param {string} path - Directory path to walk
78
* @param {WalkOptions & {return_object: true}} options - Options with return_object flag
79
* @param {WalkEventListener} [eventListener] - Optional callback for each path
80
* @returns {Object<string,fs.Stats>} - Object mapping paths to their fs.Stats objects
81
*/
82
function walkdir.sync(path, {return_object: true, ...options}, eventListener);
83
```
84
85
**Usage Example:**
86
87
```javascript
88
const stats = walkdir.sync('./project', {
89
return_object: true,
90
max_depth: 3
91
});
92
93
// Access stat information directly
94
for (const [path, stat] of Object.entries(stats)) {
95
if (stat.isFile() && path.endsWith('.json')) {
96
console.log('JSON file:', path, 'Modified:', stat.mtime);
97
}
98
}
99
100
// Check if specific path exists in results
101
if (stats['./project/package.json']) {
102
console.log('Found package.json');
103
}
104
```
105
106
### Memory Optimization
107
108
For very large directory trees, use `no_return: true` to prevent memory buildup.
109
110
```javascript { .api }
111
/**
112
* Synchronously walk directory without building result collection
113
* @param {string} path - Directory path to walk
114
* @param {WalkOptions & {no_return: true}} options - Options with no_return flag
115
* @param {WalkEventListener} eventListener - Required callback to process each path
116
* @returns {null} - No return value when no_return is true
117
*/
118
function walkdir.sync(path, {no_return: true, ...options}, eventListener);
119
```
120
121
**Usage Example:**
122
123
```javascript
124
// Process massive directory without memory overhead
125
let fileCount = 0;
126
let totalSize = 0;
127
128
walkdir.sync('/var/log', { no_return: true }, (path, stat) => {
129
if (stat.isFile()) {
130
fileCount++;
131
totalSize += stat.size;
132
}
133
});
134
135
console.log(`Processed ${fileCount} files, total size: ${totalSize} bytes`);
136
```
137
138
## Error Handling
139
140
Synchronous operations handle errors by:
141
142
- **Target path errors**: Throw exceptions immediately
143
- **Nested path errors**: Skip the problematic path and continue (no exception thrown)
144
- **Permission errors**: Skip inaccessible directories and continue traversal
145
146
```javascript
147
try {
148
const paths = walkdir.sync('./some-directory');
149
console.log('Success:', paths.length, 'items found');
150
} catch (error) {
151
console.error('Failed to read target directory:', error.message);
152
}
153
```
154
155
## Performance Considerations
156
157
- **Blocking**: Sync operations block the event loop until completion
158
- **Memory usage**: Without `no_return: true`, all paths are stored in memory
159
- **Best for**: Small to medium directory trees, build scripts, CLI tools
160
- **Avoid for**: Large directory trees, server applications, real-time applications