0
# File Operations
1
2
Core file reading, writing, and manipulation operations supporting both synchronous and asynchronous patterns with full Node.js fs API compatibility.
3
4
## Capabilities
5
6
### Write File Operations
7
8
Write data to files with various encoding and mode options.
9
10
```javascript { .api }
11
/**
12
* Synchronously write data to a file, replacing the file if it already exists
13
* @param path - File path to write to
14
* @param data - Data to write (string or Buffer)
15
* @param options - Write options including encoding, mode, and flags
16
*/
17
writeFileSync(path: string | Buffer, data: string | Buffer, options?: WriteFileOptions): void;
18
19
/**
20
* Asynchronously write data to a file, replacing the file if it already exists
21
* @param path - File path to write to
22
* @param data - Data to write (string or Buffer)
23
* @param options - Write options including encoding, mode, and flags
24
* @param callback - Completion callback
25
*/
26
writeFile(path: string | Buffer, data: string | Buffer, options?: WriteFileOptions, callback?: (err?: Error) => void): void;
27
writeFile(path: string | Buffer, data: string | Buffer, callback: (err?: Error) => void): void;
28
29
interface WriteFileOptions {
30
/** Text encoding for string data */
31
encoding?: string;
32
/** File mode (permissions) */
33
mode?: number;
34
/** File open flags */
35
flag?: string;
36
}
37
```
38
39
**Usage Examples:**
40
41
```javascript
42
// Write string content
43
fs.writeFileSync('/config.json', JSON.stringify({setting: true}));
44
45
// Write with specific encoding and mode
46
fs.writeFileSync('/data.txt', 'Hello World', {
47
encoding: 'utf8',
48
mode: 0o644,
49
flag: 'w'
50
});
51
52
// Write binary data
53
const buffer = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
54
fs.writeFileSync('/binary.dat', buffer);
55
56
// Async write with callback
57
fs.writeFile('/async.txt', 'Async content', (err) => {
58
if (err) throw err;
59
console.log('File written successfully');
60
});
61
62
// Promise-based write
63
await fs.promises.writeFile('/promise.txt', 'Promise content');
64
```
65
66
### Read File Operations
67
68
Read file contents with support for different encodings and return types.
69
70
```javascript { .api }
71
/**
72
* Synchronously read the entire contents of a file
73
* @param path - File path to read from
74
* @param options - Read options including encoding and flags
75
* @returns File contents as string (if encoding specified) or Buffer
76
*/
77
readFileSync(path: string | Buffer, options?: ReadFileOptions): string | Buffer;
78
readFileSync(path: string | Buffer, encoding: string): string;
79
80
/**
81
* Asynchronously read the entire contents of a file
82
* @param path - File path to read from
83
* @param options - Read options including encoding and flags
84
* @param callback - Completion callback with file data
85
*/
86
readFile(path: string | Buffer, options?: ReadFileOptions, callback?: (err?: Error, data?: string | Buffer) => void): void;
87
readFile(path: string | Buffer, encoding: string, callback: (err?: Error, data?: string) => void): void;
88
readFile(path: string | Buffer, callback: (err?: Error, data?: Buffer) => void): void;
89
90
interface ReadFileOptions {
91
/** Text encoding (returns string if specified, Buffer otherwise) */
92
encoding?: string;
93
/** File open flags */
94
flag?: string;
95
}
96
```
97
98
**Usage Examples:**
99
100
```javascript
101
// Read as Buffer (default)
102
const buffer = fs.readFileSync('/binary.dat');
103
console.log(buffer); // <Buffer 48 65 6c 6c 6f>
104
105
// Read as string with encoding
106
const text = fs.readFileSync('/data.txt', 'utf8');
107
console.log(text); // "Hello World"
108
109
// Read with options object
110
const content = fs.readFileSync('/config.json', { encoding: 'utf8' });
111
const config = JSON.parse(content);
112
113
// Async read with callback
114
fs.readFile('/async.txt', 'utf8', (err, data) => {
115
if (err) throw err;
116
console.log('File content:', data);
117
});
118
119
// Promise-based read
120
const data = await fs.promises.readFile('/promise.txt', 'utf8');
121
```
122
123
### File Existence
124
125
Check if files or directories exist in the filesystem.
126
127
```javascript { .api }
128
/**
129
* Synchronously test whether or not the given path exists
130
* @param path - File or directory path to check
131
* @returns true if the path exists, false otherwise
132
*/
133
existsSync(path: string | Buffer): boolean;
134
```
135
136
**Usage Examples:**
137
138
```javascript
139
// Check if file exists
140
if (fs.existsSync('/config.json')) {
141
const config = fs.readFileSync('/config.json', 'utf8');
142
console.log('Config loaded');
143
} else {
144
console.log('Config file not found');
145
}
146
147
// Check directory existence
148
const hasUploads = fs.existsSync('/uploads');
149
if (!hasUploads) {
150
fs.mkdirSync('/uploads');
151
}
152
```
153
154
### File Access Permissions
155
156
Test file accessibility and permissions.
157
158
```javascript { .api }
159
/**
160
* Synchronously test user's permissions for the file or directory
161
* @param path - File or directory path to check
162
* @param mode - Accessibility mode (defaults to fs.constants.F_OK)
163
*/
164
accessSync(path: string | Buffer, mode?: number): void;
165
166
/**
167
* Asynchronously test user's permissions for the file or directory
168
* @param path - File or directory path to check
169
* @param mode - Accessibility mode (defaults to fs.constants.F_OK)
170
* @param callback - Completion callback
171
*/
172
access(path: string | Buffer, mode?: number, callback?: (err?: Error) => void): void;
173
access(path: string | Buffer, callback: (err?: Error) => void): void;
174
```
175
176
**Usage Examples:**
177
178
```javascript
179
// Check if file exists (F_OK is default)
180
try {
181
fs.accessSync('/important.txt');
182
console.log('File exists');
183
} catch (err) {
184
console.log('File does not exist');
185
}
186
187
// Check specific permissions
188
try {
189
fs.accessSync('/sensitive.txt', fs.constants.R_OK | fs.constants.W_OK);
190
console.log('File is readable and writable');
191
} catch (err) {
192
console.log('Cannot read or write file');
193
}
194
195
// Async permission check
196
fs.access('/data.txt', fs.constants.R_OK, (err) => {
197
if (!err) {
198
console.log('File is readable');
199
} else {
200
console.log('Cannot read file');
201
}
202
});
203
```
204
205
### File Deletion
206
207
Remove files from the filesystem.
208
209
```javascript { .api }
210
/**
211
* Synchronously remove a file or symbolic link
212
* @param path - File path to remove
213
*/
214
unlinkSync(path: string | Buffer): void;
215
216
/**
217
* Asynchronously remove a file or symbolic link
218
* @param path - File path to remove
219
* @param callback - Completion callback
220
*/
221
unlink(path: string | Buffer, callback: (err?: Error) => void): void;
222
```
223
224
**Usage Examples:**
225
226
```javascript
227
// Remove file synchronously
228
try {
229
fs.unlinkSync('/temp.txt');
230
console.log('File deleted');
231
} catch (err) {
232
console.log('Error deleting file:', err.message);
233
}
234
235
// Remove file asynchronously
236
fs.unlink('/temp.txt', (err) => {
237
if (!err) {
238
console.log('File deleted successfully');
239
} else {
240
console.log('Error:', err.message);
241
}
242
});
243
244
// Promise-based deletion
245
await fs.promises.unlink('/temp.txt');
246
```
247
248
### File Copying
249
250
Copy files with optional flags for behavior control.
251
252
```javascript { .api }
253
/**
254
* Synchronously copy src to dest, overwriting dest if it already exists
255
* @param src - Source file path
256
* @param dest - Destination file path
257
* @param flags - Copy operation flags (optional)
258
*/
259
copyFileSync(src: string | Buffer, dest: string | Buffer, flags?: number): void;
260
261
/**
262
* Asynchronously copy src to dest
263
* @param src - Source file path
264
* @param dest - Destination file path
265
* @param flags - Copy operation flags (optional)
266
* @param callback - Completion callback
267
*/
268
copyFile(src: string | Buffer, dest: string | Buffer, flags?: number, callback?: (err?: Error) => void): void;
269
copyFile(src: string | Buffer, dest: string | Buffer, callback: (err?: Error) => void): void;
270
```
271
272
**Usage Examples:**
273
274
```javascript
275
// Simple file copy
276
fs.copyFileSync('/source.txt', '/backup.txt');
277
278
// Copy with exclusive flag (fail if destination exists)
279
try {
280
fs.copyFileSync('/source.txt', '/backup.txt', fs.constants.COPYFILE_EXCL);
281
console.log('File copied');
282
} catch (err) {
283
console.log('Destination already exists');
284
}
285
286
// Async copy
287
fs.copyFile('/source.txt', '/backup.txt', (err) => {
288
if (!err) {
289
console.log('File copied successfully');
290
}
291
});
292
293
// Promise-based copy
294
await fs.promises.copyFile('/source.txt', '/backup.txt');
295
```
296
297
### File Truncation
298
299
Truncate files to a specific length.
300
301
```javascript { .api }
302
/**
303
* Synchronously truncate a file to a specified length
304
* @param path - File path or file descriptor
305
* @param len - Target length in bytes (defaults to 0)
306
*/
307
truncateSync(path: string | Buffer | number, len?: number): void;
308
309
/**
310
* Asynchronously truncate a file to a specified length
311
* @param path - File path or file descriptor
312
* @param len - Target length in bytes (defaults to 0)
313
* @param callback - Completion callback
314
*/
315
truncate(path: string | Buffer, len?: number, callback?: (err?: Error) => void): void;
316
truncate(path: string | Buffer, callback: (err?: Error) => void): void;
317
```
318
319
**Usage Examples:**
320
321
```javascript
322
// Truncate file to 0 bytes (empty it)
323
fs.truncateSync('/large-file.txt');
324
325
// Truncate to specific length
326
fs.truncateSync('/data.txt', 100); // Keep only first 100 bytes
327
328
// Async truncation
329
fs.truncate('/log.txt', 1000, (err) => {
330
if (!err) {
331
console.log('File truncated to 1000 bytes');
332
}
333
});
334
335
// Promise-based truncation
336
await fs.promises.truncate('/data.txt', 50);
337
```
338
339
## Constants
340
341
File operation constants available via `fs.constants`:
342
343
```javascript { .api }
344
// File access constants
345
F_OK: 0 // File exists
346
R_OK: 4 // File is readable
347
W_OK: 2 // File is writable
348
X_OK: 1 // File is executable
349
350
// Copy file constants
351
COPYFILE_EXCL: 1 // Fail if destination exists
352
COPYFILE_FICLONE: 2 // Clone file if possible
353
```