0
# Directory Operations
1
2
Directory creation, listing, and removal operations with support for recursive operations and various output formats including file type information.
3
4
## Capabilities
5
6
### Directory Creation
7
8
Create directories with support for recursive creation and permission settings.
9
10
```javascript { .api }
11
/**
12
* Synchronously create a directory
13
* @param path - Directory path to create
14
* @param options - Creation options including recursive and mode
15
*/
16
mkdirSync(path: string | Buffer, options?: MkdirOptions): void;
17
mkdirSync(path: string | Buffer, mode?: number): void;
18
19
/**
20
* Asynchronously create a directory
21
* @param path - Directory path to create
22
* @param options - Creation options including recursive and mode
23
* @param callback - Completion callback
24
*/
25
mkdir(path: string | Buffer, options?: MkdirOptions, callback?: (err?: Error) => void): void;
26
mkdir(path: string | Buffer, mode?: number, callback?: (err?: Error) => void): void;
27
mkdir(path: string | Buffer, callback: (err?: Error) => void): void;
28
29
interface MkdirOptions {
30
/** Create parent directories if they don't exist */
31
recursive?: boolean;
32
/** Directory permissions mode */
33
mode?: number;
34
}
35
```
36
37
**Usage Examples:**
38
39
```javascript
40
// Create single directory
41
fs.mkdirSync('/uploads');
42
43
// Create with specific permissions
44
fs.mkdirSync('/secure', { mode: 0o755 });
45
46
// Create directory tree recursively
47
fs.mkdirSync('/app/data/cache', { recursive: true });
48
49
// Async directory creation
50
fs.mkdir('/temp', (err) => {
51
if (!err) {
52
console.log('Directory created');
53
}
54
});
55
56
// Promise-based creation
57
await fs.promises.mkdir('/logs', { recursive: true });
58
```
59
60
### Directory Listing
61
62
List directory contents with various output formats and options.
63
64
```javascript { .api }
65
/**
66
* Synchronously read the contents of a directory
67
* @param path - Directory path to read
68
* @param options - Read options including encoding and withFileTypes
69
* @returns Array of filenames, Buffers, or Dirent objects
70
*/
71
readdirSync(path: string | Buffer, options?: ReaddirOptions): string[] | Buffer[] | Dirent[];
72
readdirSync(path: string | Buffer, encoding?: string): string[] | Buffer[];
73
74
/**
75
* Asynchronously read the contents of a directory
76
* @param path - Directory path to read
77
* @param options - Read options including encoding and withFileTypes
78
* @param callback - Completion callback with directory entries
79
*/
80
readdir(path: string | Buffer, options?: ReaddirOptions, callback?: (err?: Error, files?: string[] | Buffer[] | Dirent[]) => void): void;
81
readdir(path: string | Buffer, encoding: string, callback: (err?: Error, files?: string[] | Buffer[]) => void): void;
82
readdir(path: string | Buffer, callback: (err?: Error, files?: string[]) => void): void;
83
84
interface ReaddirOptions {
85
/** Text encoding for filenames */
86
encoding?: string;
87
/** Return Dirent objects with file type information */
88
withFileTypes?: boolean;
89
}
90
91
interface Dirent {
92
/** Entry name (filename or directory name) */
93
name: string | Buffer;
94
95
/** Check if entry is a regular file */
96
isFile(): boolean;
97
/** Check if entry is a directory */
98
isDirectory(): boolean;
99
/** Check if entry is a symbolic link */
100
isSymbolicLink(): boolean;
101
/** Check if entry is a block device */
102
isBlockDevice(): boolean;
103
/** Check if entry is a character device */
104
isCharacterDevice(): boolean;
105
/** Check if entry is a FIFO pipe */
106
isFIFO(): boolean;
107
/** Check if entry is a socket */
108
isSocket(): boolean;
109
}
110
```
111
112
**Usage Examples:**
113
114
```javascript
115
// List directory as string array
116
const files = fs.readdirSync('/home');
117
console.log(files); // ['documents', 'downloads', 'file.txt']
118
119
// Get detailed file information
120
const entries = fs.readdirSync('/home', { withFileTypes: true });
121
entries.forEach(entry => {
122
if (entry.isFile()) {
123
console.log(`File: ${entry.name}`);
124
} else if (entry.isDirectory()) {
125
console.log(`Directory: ${entry.name}`);
126
}
127
});
128
129
// List with specific encoding
130
const bufferNames = fs.readdirSync('/data', { encoding: 'buffer' });
131
132
// Async directory listing
133
fs.readdir('/projects', (err, files) => {
134
if (!err) {
135
console.log('Project directories:', files);
136
}
137
});
138
139
// Promise-based listing with file types
140
const entries = await fs.promises.readdir('/app', { withFileTypes: true });
141
const directories = entries
142
.filter(entry => entry.isDirectory())
143
.map(entry => entry.name);
144
```
145
146
### Directory Removal
147
148
Remove empty directories from the filesystem.
149
150
```javascript { .api }
151
/**
152
* Synchronously remove a directory (must be empty)
153
* @param path - Directory path to remove
154
*/
155
rmdirSync(path: string | Buffer): void;
156
157
/**
158
* Asynchronously remove a directory (must be empty)
159
* @param path - Directory path to remove
160
* @param callback - Completion callback
161
*/
162
rmdir(path: string | Buffer, callback: (err?: Error) => void): void;
163
```
164
165
**Usage Examples:**
166
167
```javascript
168
// Remove empty directory
169
try {
170
fs.rmdirSync('/empty-dir');
171
console.log('Directory removed');
172
} catch (err) {
173
console.log('Error:', err.message); // Directory not empty
174
}
175
176
// Async directory removal
177
fs.rmdir('/temp-dir', (err) => {
178
if (!err) {
179
console.log('Directory removed successfully');
180
} else {
181
console.log('Cannot remove directory:', err.message);
182
}
183
});
184
185
// Promise-based removal
186
await fs.promises.rmdir('/old-cache');
187
```
188
189
### Advanced Removal
190
191
Remove files and directories with advanced options including recursive removal.
192
193
```javascript { .api }
194
/**
195
* Synchronously remove files and directories with advanced options
196
* @param path - Path to remove (file or directory)
197
* @param options - Removal options including recursive and force
198
*/
199
rmSync(path: string | Buffer, options?: RmOptions): void;
200
201
interface RmOptions {
202
/** Remove directories and their contents recursively */
203
recursive?: boolean;
204
/** Don't throw error if path doesn't exist */
205
force?: boolean;
206
}
207
```
208
209
**Usage Examples:**
210
211
```javascript
212
// Remove file or empty directory
213
fs.rmSync('/target');
214
215
// Remove directory and all contents recursively
216
fs.rmSync('/project-folder', { recursive: true });
217
218
// Force removal (don't error if path doesn't exist)
219
fs.rmSync('/maybe-exists', { force: true });
220
221
// Recursive removal with force
222
fs.rmSync('/old-build', { recursive: true, force: true });
223
```
224
225
### Temporary Directory Creation
226
227
Create temporary directories with random names.
228
229
```javascript { .api }
230
/**
231
* Synchronously create a unique temporary directory
232
* @param prefix - Directory name prefix
233
* @param options - Creation options including encoding
234
* @returns Path to created temporary directory
235
*/
236
mkdtempSync(prefix: string, options?: MktempOptions): string;
237
238
interface MktempOptions {
239
/** Encoding for returned path */
240
encoding?: string;
241
}
242
```
243
244
**Usage Examples:**
245
246
```javascript
247
// Create temp directory with prefix
248
const tempDir = fs.mkdtempSync('/tmp/myapp-');
249
console.log(tempDir); // '/tmp/myapp-A1B2C3'
250
251
// Create with custom encoding
252
const tempPath = fs.mkdtempSync('/tmp/build-', { encoding: 'utf8' });
253
254
// Use temp directory for processing
255
const processingDir = fs.mkdtempSync('/tmp/process-');
256
try {
257
// ... do work in processingDir
258
fs.writeFileSync(`${processingDir}/data.json`, JSON.stringify(data));
259
// ... process files
260
} finally {
261
// Clean up temp directory
262
fs.rmSync(processingDir, { recursive: true });
263
}
264
```
265
266
## Working with Directory Paths
267
268
```javascript
269
// Check if path is directory
270
const stats = fs.statSync('/path');
271
if (stats.isDirectory()) {
272
console.log('Is a directory');
273
}
274
275
// Create nested directory structure
276
fs.mkdirSync('/app/public/assets/images', { recursive: true });
277
278
// List all files in directory tree (recursive helper)
279
function listAllFiles(dir) {
280
const results = [];
281
const entries = fs.readdirSync(dir, { withFileTypes: true });
282
283
for (const entry of entries) {
284
const fullPath = `${dir}/${entry.name}`;
285
if (entry.isDirectory()) {
286
results.push(...listAllFiles(fullPath));
287
} else {
288
results.push(fullPath);
289
}
290
}
291
292
return results;
293
}
294
295
const allFiles = listAllFiles('/project');
296
```
297
298
## Error Handling
299
300
Common directory operation errors:
301
302
- `ENOENT` - Directory or parent directory doesn't exist
303
- `EEXIST` - Directory already exists (mkdir without recursive)
304
- `ENOTDIR` - Path exists but is not a directory
305
- `ENOTEMPTY` - Directory not empty (rmdir)
306
- `EPERM` - Permission denied