-
-
Notifications
You must be signed in to change notification settings - Fork 35.6k
Expand file tree
/
Copy pathfs.md
More file actions
4661 lines (3761 loc) Β· 143 KB
/
fs.md
File metadata and controls
4661 lines (3761 loc) Β· 143 KB
Edit and raw actions
OlderNewer
Β
1
# File System
2
3
<!--introduced_in=v0.10.0-->
4
5
> Stability: 2 - Stable
6
7
<!--name=fs-->
8
9
The `fs` module provides an API for interacting with the file system in a
10
manner closely modeled around standard POSIX functions.
11
12
To use this module:
13
14
```js
15
const fs = require('fs');
16
```
17
18
All file system operations have synchronous and asynchronous forms.
19
20
The asynchronous form always takes a completion callback as its last argument.
21
The arguments passed to the completion callback depend on the method, but the
22
first argument is always reserved for an exception. If the operation was
23
completed successfully, then the first argument will be `null` or `undefined`.
24
25
```js
26
const fs = require('fs');
27
28
fs.unlink('/tmp/hello', (err) => {
29
if (err) throw err;
30
console.log('successfully deleted /tmp/hello');
31
});
32
```
33
34
Exceptions that occur using synchronous operations are thrown immediately and
35
may be handled using `try`/`catch`, or may be allowed to bubble up.
36
37
```js
38
const fs = require('fs');
39
40
try {
41
fs.unlinkSync('/tmp/hello');
42
console.log('successfully deleted /tmp/hello');
43
} catch (err) {
44
// handle the error
45
}
46
```
47
48
There is no guaranteed ordering when using asynchronous methods. So the
49
following is prone to error because the `fs.stat()` operation may complete
50
before the `fs.rename()` operation:
51
52
```js
53
fs.rename('/tmp/hello', '/tmp/world', (err) => {
54
if (err) throw err;
55
console.log('renamed complete');
56
});
57
fs.stat('/tmp/world', (err, stats) => {
58
if (err) throw err;
59
console.log(`stats: ${JSON.stringify(stats)}`);
60
});
61
```
62
63
To correctly order the operations, move the `fs.stat()` call into the callback
64
of the `fs.rename()` operation:
65
66
```js
67
fs.rename('/tmp/hello', '/tmp/world', (err) => {
68
if (err) throw err;
69
fs.stat('/tmp/world', (err, stats) => {
70
if (err) throw err;
71
console.log(`stats: ${JSON.stringify(stats)}`);
72
});
73
});
74
```
75
76
In busy processes, the programmer is _strongly encouraged_ to use the
77
asynchronous versions of these calls. The synchronous versions will block
78
the entire process until they complete β halting all connections.
79
80
While it is not recommended, most fs functions allow the callback argument to
81
be omitted, in which case a default callback is used that rethrows errors. To
82
get a trace to the original call site, set the `NODE_DEBUG` environment
83
variable:
84
85
Omitting the callback function on asynchronous fs functions is deprecated and
86
may result in an error being thrown in the future.
87
88
```txt
89
$ cat script.js
90
function bad() {
91
require('fs').readFile('/');
92
}
93
bad();
94
95
$ env NODE_DEBUG=fs node script.js
96
fs.js:88
97
throw backtrace;
98
^
99
Error: EISDIR: illegal operation on a directory, read
100
<stack trace.>
101
```
102
103
## File paths
104
105
Most `fs` operations accept filepaths that may be specified in the form of
106
a string, a [`Buffer`][], or a [`URL`][] object using the `file:` protocol.
107
108
String form paths are interpreted as UTF-8 character sequences identifying
109
the absolute or relative filename. Relative paths will be resolved relative
110
to the current working directory as specified by `process.cwd()`.
111
112
Example using an absolute path on POSIX:
113
114
```js
115
const fs = require('fs');
116
117
fs.open('/open/some/file.txt', 'r', (err, fd) => {
118
if (err) throw err;
119
fs.close(fd, (err) => {
120
if (err) throw err;
121
});
122
});
123
```
124
125
Example using a relative path on POSIX (relative to `process.cwd()`):
126
127
```js
128
fs.open('file.txt', 'r', (err, fd) => {
129
if (err) throw err;
130
fs.close(fd, (err) => {
131
if (err) throw err;
132
});
133
});
134
```
135
136
Paths specified using a [`Buffer`][] are useful primarily on certain POSIX
137
operating systems that treat file paths as opaque byte sequences. On such
138
systems, it is possible for a single file path to contain sub-sequences that
139
use multiple character encodings. As with string paths, `Buffer` paths may
140
be relative or absolute:
141
142
Example using an absolute path on POSIX:
143
144
```js
145
fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
146
if (err) throw err;
147
fs.close(fd, (err) => {
148
if (err) throw err;
149
});
150
});
151
```
152
153
On Windows, Node.js follows the concept of per-drive working directory. This
154
behavior can be observed when using a drive path without a backslash. For
155
example `fs.readdirSync('c:\\')` can potentially return a different result than
156
`fs.readdirSync('c:')`. For more information, see
157
[this MSDN page][MSDN-Rel-Path].
158
159
### URL object support
160
<!-- YAML
161
added: v7.6.0
162
-->
163
For most `fs` module functions, the `path` or `filename` argument may be passed
164
as a WHATWG [`URL`][] object. Only [`URL`][] objects using the `file:` protocol
165
are supported.
166
167
```js
168
const fs = require('fs');
169
const fileUrl = new URL('file:///tmp/hello');
170
171
fs.readFileSync(fileUrl);
172
```
173
174
`file:` URLs are always absolute paths.
175
176
Using WHATWG [`URL`][] objects might introduce platform-specific behaviors.
177
178
On Windows, `file:` URLs with a hostname convert to UNC paths, while `file:`
179
URLs with drive letters convert to local absolute paths. `file:` URLs without a
180
hostname nor a drive letter will result in a throw:
181
182
```js
183
// On Windows :
184
185
// - WHATWG file URLs with hostname convert to UNC path
186
// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
187
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
188
189
// - WHATWG file URLs with drive letters convert to absolute path
190
// file:///C:/tmp/hello => C:\tmp\hello
191
fs.readFileSync(new URL('file:///C:/tmp/hello'));
192
193
// - WHATWG file URLs without hostname must have a drive letters
194
fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
195
fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
196
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
197
```
198
199
`file:` URLs with drive letters must use `:` as a separator just after
200
the drive letter. Using another separator will result in a throw.
201
202
On all other platforms, `file:` URLs with a hostname are unsupported and will
203
result in a throw:
204
205
```js
206
// On other platforms:
207
208
// - WHATWG file URLs with hostname are unsupported
209
// file://hostname/p/a/t/h/file => throw!
210
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
211
// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
212
213
// - WHATWG file URLs convert to absolute path
214
// file:///tmp/hello => /tmp/hello
215
fs.readFileSync(new URL('file:///tmp/hello'));
216
```
217
218
A `file:` URL having encoded slash characters will result in a throw on all
219
platforms:
220
221
```js
222
// On Windows
223
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
224
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
225
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
226
\ or / characters */
227
228
// On POSIX
229
fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
230
fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
231
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
232
/ characters */
233
```
234
On Windows, `file:` URLs having encoded backslash will result in a throw:
235
236
```js
237
// On Windows
238
fs.readFileSync(new URL('file:///C:/path/%5C'));
239
fs.readFileSync(new URL('file:///C:/path/%5c'));
240
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
241
\ or / characters */
242
```
243
244
## File Descriptors
245
246
On POSIX systems, for every process, the kernel maintains a table of currently
247
open files and resources. Each open file is assigned a simple numeric
248
identifier called a *file descriptor*. At the system-level, all file system
249
operations use these file descriptors to identify and track each specific
250
file. Windows systems use a different but conceptually similar mechanism for
251
tracking resources. To simplify things for users, Node.js abstracts away the
252
specific differences between operating systems and assigns all open files a
253
numeric file descriptor.
254
255
The `fs.open()` method is used to allocate a new file descriptor. Once
256
allocated, the file descriptor may be used to read data from, write data to,
257
or request information about the file.
258
259
```js
260
fs.open('/open/some/file.txt', 'r', (err, fd) => {
261
if (err) throw err;
262
fs.fstat(fd, (err, stat) => {
263
if (err) throw err;
264
// use stat
265
266
// always close the file descriptor!
267
fs.close(fd, (err) => {
268
if (err) throw err;
269
});
270
});
271
});
272
```
273
274
Most operating systems limit the number of file descriptors that may be open
275
at any given time so it is critical to close the descriptor when operations
276
are completed. Failure to do so will result in a memory leak that will
277
eventually cause an application to crash.
278
279
## Threadpool Usage
280
281
All file system APIs except `fs.FSWatcher()` and those that are explicitly
282
synchronous use libuv's threadpool, which can have surprising and negative
283
performance implications for some applications. See the
284
[`UV_THREADPOOL_SIZE`][] documentation for more information.
285
286
## Class: fs.FSWatcher
287
<!-- YAML
288
added: v0.5.8
289
-->
290
291
A successful call to [`fs.watch()`][] method will return a new `fs.FSWatcher`
292
object.
293
294
All `fs.FSWatcher` objects are [`EventEmitter`][]'s that will emit a `'change'`
295
event whenever a specific watched file is modified.
296
297
### Event: 'change'
298
<!-- YAML
299
added: v0.5.8
300
-->
301
302
* `eventType` {string} The type of change event that has occurred
303
* `filename` {string|Buffer} The filename that changed (if relevant/available)
304
305
Emitted when something changes in a watched directory or file.
306
See more details in [`fs.watch()`][].
307
308
The `filename` argument may not be provided depending on operating system
309
support. If `filename` is provided, it will be provided as a `Buffer` if
310
`fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise
311
`filename` will be a UTF-8 string.
312
313
```js
314
// Example when handled through fs.watch() listener
315
fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
316
if (filename) {
317
console.log(filename);
318
// Prints: <Buffer ...>
319
}
320
});
321
```
322
323
### Event: 'close'
324
<!-- YAML
325
added: v10.0.0
326
-->
327
328
Emitted when the watcher stops watching for changes. The closed
329
`fs.FSWatcher` object is no longer usable in the event handler.
330
331
### Event: 'error'
332
<!-- YAML
333
added: v0.5.8
334
-->
335
336
* `error` {Error}
337
338
Emitted when an error occurs while watching the file. The errored
339
`fs.FSWatcher` object is no longer usable in the event handler.
340
341
### watcher.close()
342
<!-- YAML
343
added: v0.5.8
344
-->
345
346
Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the
347
`fs.FSWatcher` object is no longer usable.
348
349
## Class: fs.ReadStream
350
<!-- YAML
351
added: v0.1.93
352
-->
353
354
A successful call to `fs.createReadStream()` will return a new `fs.ReadStream`
355
object.
356
357
All `fs.ReadStream` objects are [Readable Streams][].
358
359
### Event: 'close'
360
<!-- YAML
361
added: v0.1.93
362
-->
363
364
Emitted when the `fs.ReadStream`'s underlying file descriptor has been closed.
365
366
### Event: 'open'
367
<!-- YAML
368
added: v0.1.93
369
-->
370
371
* `fd` {integer} Integer file descriptor used by the `ReadStream`.
372
373
Emitted when the `fs.ReadStream`'s file descriptor has been opened.
374
375
### Event: 'ready'
376
<!-- YAML
377
added: v9.11.0
378
-->
379
380
Emitted when the `fs.ReadStream` is ready to be used.
381
382
Fires immediately after `'open'`.
383
384
### readStream.bytesRead
385
<!-- YAML
386
added: v6.4.0
387
-->
388
389
* {number}
390
391
The number of bytes that have been read so far.
392
393
### readStream.path
394
<!-- YAML
395
added: v0.1.93
396
-->
397
398
* {string|Buffer}
399
400
The path to the file the stream is reading from as specified in the first
401
argument to `fs.createReadStream()`. If `path` is passed as a string, then
402
`readStream.path` will be a string. If `path` is passed as a `Buffer`, then
403
`readStream.path` will be a `Buffer`.
404
405
## Class: fs.Stats
406
<!-- YAML
407
added: v0.1.21
408
changes:
409
- version: v8.1.0
410
pr-url: https://github.com/nodejs/node/pull/13173
411
description: Added times as numbers.
412
-->
413
414
A `fs.Stats` object provides information about a file.
415
416
Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and
417
their synchronous counterparts are of this type.
418
If `bigint` in the `options` passed to those methods is true, the numeric values
419
will be `bigint` instead of `number`.
420
421
```console
422
Stats {
423
dev: 2114,
424
ino: 48064969,
425
mode: 33188,
426
nlink: 1,
427
uid: 85,
428
gid: 100,
429
rdev: 0,
430
size: 527,
431
blksize: 4096,
432
blocks: 8,
433
atimeMs: 1318289051000.1,
434
mtimeMs: 1318289051000.1,
435
ctimeMs: 1318289051000.1,
436
birthtimeMs: 1318289051000.1,
437
atime: Mon, 10 Oct 2011 23:24:11 GMT,
438
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
439
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
440
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
441
```
442
443
`bigint` version:
444
445
```console
446
Stats {
447
dev: 2114n,
448
ino: 48064969n,
449
mode: 33188n,
450
nlink: 1n,
451
uid: 85n,
452
gid: 100n,
453
rdev: 0n,
454
size: 527n,
455
blksize: 4096n,
456
blocks: 8n,
457
atimeMs: 1318289051000n,
458
mtimeMs: 1318289051000n,
459
ctimeMs: 1318289051000n,
460
birthtimeMs: 1318289051000n,
461
atime: Mon, 10 Oct 2011 23:24:11 GMT,
462
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
463
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
464
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
465
```
466
467
### stats.isBlockDevice()
468
<!-- YAML
469
added: v0.1.10
470
-->
471
472
* Returns: {boolean}
473
474
Returns `true` if the `fs.Stats` object describes a block device.
475
476
### stats.isCharacterDevice()
477
<!-- YAML
478
added: v0.1.10
479
-->
480
481
* Returns: {boolean}
482
483
Returns `true` if the `fs.Stats` object describes a character device.
484
485
### stats.isDirectory()
486
<!-- YAML
487
added: v0.1.10
488
-->
489
490
* Returns: {boolean}
491
492
Returns `true` if the `fs.Stats` object describes a file system directory.
493
494
### stats.isFIFO()
495
<!-- YAML
496
added: v0.1.10
497
-->
498
499
* Returns: {boolean}
500
501
Returns `true` if the `fs.Stats` object describes a first-in-first-out (FIFO)
502
pipe.
503
504
### stats.isFile()
505
<!-- YAML
506
added: v0.1.10
507
-->
508
509
* Returns: {boolean}
510
511
Returns `true` if the `fs.Stats` object describes a regular file.
512
513
### stats.isSocket()
514
<!-- YAML
515
added: v0.1.10
516
-->
517
518
* Returns: {boolean}
519
520
Returns `true` if the `fs.Stats` object describes a socket.
521
522
### stats.isSymbolicLink()
523
<!-- YAML
524
added: v0.1.10
525
-->
526
527
* Returns: {boolean}
528
529
Returns `true` if the `fs.Stats` object describes a symbolic link.
530
531
This method is only valid when using [`fs.lstat()`][].
532
533
### stats.dev
534
535
* {number|bigint}
536
537
The numeric identifier of the device containing the file.
538
539
### stats.ino
540
541
* {number|bigint}
542
543
The file system specific "Inode" number for the file.
544
545
### stats.mode
546
547
* {number|bigint}
548
549
A bit-field describing the file type and mode.
550
551
### stats.nlink
552
553
* {number|bigint}
554
555
The number of hard-links that exist for the file.
556
557
### stats.uid
558
559
* {number|bigint}
560
561
The numeric user identifier of the user that owns the file (POSIX).
562
563
### stats.gid
564
565
* {number|bigint}
566
567
The numeric group identifier of the group that owns the file (POSIX).
568
569
### stats.rdev
570
571
* {number|bigint}
572
573
A numeric device identifier if the file is considered "special".
574
575
### stats.size
576
577
* {number|bigint}
578
579
The size of the file in bytes.
580
581
### stats.blksize
582
583
* {number|bigint}
584
585
The file system block size for i/o operations.
586
587
### stats.blocks
588
589
* {number|bigint}
590
591
The number of blocks allocated for this file.
592
593
### stats.atimeMs
594
<!-- YAML
595
added: v8.1.0
596
-->
597
598
* {number|bigint}
599
600
The timestamp indicating the last time this file was accessed expressed in
601
milliseconds since the POSIX Epoch.
602
603
### stats.mtimeMs
604
<!-- YAML
605
added: v8.1.0
606
-->
607
608
* {number|bigint}
609
610
The timestamp indicating the last time this file was modified expressed in
611
milliseconds since the POSIX Epoch.
612
613
### stats.ctimeMs
614
<!-- YAML
615
added: v8.1.0
616
-->
617
618
* {number|bigint}
619
620
The timestamp indicating the last time the file status was changed expressed
621
in milliseconds since the POSIX Epoch.
622
623
### stats.birthtimeMs
624
<!-- YAML
625
added: v8.1.0
626
-->
627
628
* {number|bigint}
629
630
The timestamp indicating the creation time of this file expressed in
631
milliseconds since the POSIX Epoch.
632
633
### stats.atime
634
<!-- YAML
635
added: v0.11.13
636
-->
637
638
* {Date}
639
640
The timestamp indicating the last time this file was accessed.
641
642
### stats.mtime
643
<!-- YAML
644
added: v0.11.13
645
-->
646
647
* {Date}
648
649
The timestamp indicating the last time this file was modified.
650
651
### stats.ctime
652
<!-- YAML
653
added: v0.11.13
654
-->
655
656
* {Date}
657
658
The timestamp indicating the last time the file status was changed.
659
660
### stats.birthtime
661
<!-- YAML
662
added: v0.11.13
663
-->
664
665
* {Date}
666
667
The timestamp indicating the creation time of this file.
668
669
### Stat Time Values
670
671
The `atimeMs`, `mtimeMs`, `ctimeMs`, `birthtimeMs` properties are
672
[numbers][MDN-Number] that hold the corresponding times in milliseconds. Their
673
precision is platform specific. `atime`, `mtime`, `ctime`, and `birthtime` are
674
[`Date`][MDN-Date] object alternate representations of the various times. The
675
`Date` and number values are not connected. Assigning a new number value, or
676
mutating the `Date` value, will not be reflected in the corresponding alternate
677
representation.
678
679
The times in the stat object have the following semantics:
680
681
* `atime` "Access Time" - Time when file data last accessed. Changed
682
by the mknod(2), utimes(2), and read(2) system calls.
683
* `mtime` "Modified Time" - Time when file data last modified.
684
Changed by the mknod(2), utimes(2), and write(2) system calls.
685
* `ctime` "Change Time" - Time when file status was last changed
686
(inode data modification). Changed by the chmod(2), chown(2),
687
link(2), mknod(2), rename(2), unlink(2), utimes(2),
688
read(2), and write(2) system calls.
689
* `birthtime` "Birth Time" - Time of file creation. Set once when the
690
file is created. On filesystems where birthtime is not available,
691
this field may instead hold either the `ctime` or
692
`1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). This value may be greater
693
than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants,
694
also set if the `atime` is explicitly set to an earlier value than the current
695
`birthtime` using the utimes(2) system call.
696
697
Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As
698
of 0.12, `ctime` is not "creation time", and on Unix systems, it never was.
699
700
## Class: fs.WriteStream
701
<!-- YAML
702
added: v0.1.93
703
-->
704
705
`WriteStream` is a [Writable Stream][].
706
707
### Event: 'close'
708
<!-- YAML
709
added: v0.1.93
710
-->
711
712
Emitted when the `WriteStream`'s underlying file descriptor has been closed.
713
714
### Event: 'open'
715
<!-- YAML
716
added: v0.1.93
717
-->
718
719
* `fd` {integer} Integer file descriptor used by the `WriteStream`.
720
721
Emitted when the `WriteStream`'s file is opened.
722
723
### Event: 'ready'
724
<!-- YAML
725
added: v9.11.0
726
-->
727
728
Emitted when the `fs.WriteStream` is ready to be used.
729
730
Fires immediately after `'open'`.
731
732
### writeStream.bytesWritten
733
<!-- YAML
734
added: v0.4.7
735
-->
736
737
The number of bytes written so far. Does not include data that is still queued
738
for writing.
739
740
### writeStream.path
741
<!-- YAML
742
added: v0.1.93
743
-->
744
745
The path to the file the stream is writing to as specified in the first
746
argument to `fs.createWriteStream()`. If `path` is passed as a string, then
747
`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then
748
`writeStream.path` will be a `Buffer`.
749
750
## fs.access(path[, mode], callback)
751
<!-- YAML
752
added: v0.11.15
753
changes:
754
- version: v7.6.0
755
pr-url: https://github.com/nodejs/node/pull/10739
756
description: The `path` parameter can be a WHATWG `URL` object using `file:`
757
protocol. Support is currently still *experimental*.
758
- version: v6.3.0
759
pr-url: https://github.com/nodejs/node/pull/6534
760
description: The constants like `fs.R_OK`, etc which were present directly
761
on `fs` were moved into `fs.constants` as a soft deprecation.
762
Thus for Node.js `< v6.3.0` use `fs`
763
to access those constants, or
764
do something like `(fs.constants || fs).R_OK` to work with all
765
versions.
766
-->
767
768
* `path` {string|Buffer|URL}
769
* `mode` {integer} **Default:** `fs.constants.F_OK`
770
* `callback` {Function}
771
* `err` {Error}
772
773
Tests a user's permissions for the file or directory specified by `path`.
774
The `mode` argument is an optional integer that specifies the accessibility
775
checks to be performed. Check [File Access Constants][] for possible values
776
of `mode`. It is possible to create a mask consisting of the bitwise OR of
777
two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
778
779
The final argument, `callback`, is a callback function that is invoked with
780
a possible error argument. If any of the accessibility checks fail, the error
781
argument will be an `Error` object. The following examples check if
782
`package.json` exists, and if it is readable or writable.
783
784
```js
785
const file = 'package.json';
786
787
// Check if the file exists in the current directory.
788
fs.access(file, fs.constants.F_OK, (err) => {
789
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
790
});
791
792
// Check if the file is readable.
793
fs.access(file, fs.constants.R_OK, (err) => {
794
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
795
});
796
797
// Check if the file is writable.
798
fs.access(file, fs.constants.W_OK, (err) => {
799
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
800
});
801
802
// Check if the file exists in the current directory, and if it is writable.
803
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
804
if (err) {
805
console.error(
806
`${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
807
} else {
808
console.log(`${file} exists, and it is writable`);
809
}
810
});
811
```
812
813
Using `fs.access()` to check for the accessibility of a file before calling
814
`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing
815
so introduces a race condition, since other processes may change the file's
816
state between the two calls. Instead, user code should open/read/write the
817
file directly and handle the error raised if the file is not accessible.
818
819
**write (NOT RECOMMENDED)**
820
821
```js
822
fs.access('myfile', (err) => {
823
if (!err) {
824
console.error('myfile already exists');
825
return;
826
}
827
828
fs.open('myfile', 'wx', (err, fd) => {
829
if (err) throw err;
830
writeMyData(fd);
831
});
832
});
833
```
834
835
**write (RECOMMENDED)**
836
837
```js
838
fs.open('myfile', 'wx', (err, fd) => {
839
if (err) {
840
if (err.code === 'EEXIST') {
841
console.error('myfile already exists');
842
return;
843
}
844
845
throw err;
846
}
847
848
writeMyData(fd);
849
});
850
```
851
852
**read (NOT RECOMMENDED)**
853
854
```js
855
fs.access('myfile', (err) => {
856
if (err) {
857
if (err.code === 'ENOENT') {
858
console.error('myfile does not exist');
859
return;
860
}
861
862
throw err;
863
}
864
865
fs.open('myfile', 'r', (err, fd) => {
866
if (err) throw err;
867
readMyData(fd);
868
});
869
});
870
```
871
872
**read (RECOMMENDED)**
873
874
```js
875
fs.open('myfile', 'r', (err, fd) => {
876
if (err) {
877
if (err.code === 'ENOENT') {
878
console.error('myfile does not exist');
879
return;
880
}
881
882
throw err;
883
}
884
885
readMyData(fd);
886
});
887
```
888
889
The "not recommended" examples above check for accessibility and then use the
890
file; the "recommended" examples are better because they use the file directly
891
and handle the error, if any.
892
893
In general, check for the accessibility of a file only if the file will not be
894
used directly, for example when its accessibility is a signal from another
895
process.
896
897
## fs.accessSync(path[, mode])
898
<!-- YAML
899
added: v0.11.15
900
changes:
901
- version: v7.6.0
902
pr-url: https://github.com/nodejs/node/pull/10739
903
description: The `path` parameter can be a WHATWG `URL` object using `file:`
904
protocol. Support is currently still *experimental*.
905
-->
906
907
* `path` {string|Buffer|URL}
908
* `mode` {integer} **Default:** `fs.constants.F_OK`
909
910
Synchronously tests a user's permissions for the file or directory specified
911
by `path`. The `mode` argument is an optional integer that specifies the
912
accessibility checks to be performed. Check [File Access Constants][] for
913
possible values of `mode`. It is possible to create a mask consisting of
914
the bitwise OR of two or more values
915
(e.g. `fs.constants.W_OK | fs.constants.R_OK`).
916
917
If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
918
the method will return `undefined`.
919
920
```js
921
try {
922
fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
923
console.log('can read/write');
924
} catch (err) {
925
console.error('no access!');
926
}
927
```
928
929
## fs.appendFile(path, data[, options], callback)
930
<!-- YAML
931
added: v0.6.7
932
changes:
933
- version: v10.0.0
934
pr-url: https://github.com/nodejs/node/pull/12562
935
description: The `callback` parameter is no longer optional. Not passing
936
it will throw a `TypeError` at runtime.
937
- version: v7.0.0
938
pr-url: https://github.com/nodejs/node/pull/7897
939
description: The `callback` parameter is no longer optional. Not passing
940
it will emit a deprecation warning with id DEP0013.
941
- version: v7.0.0
942
pr-url: https://github.com/nodejs/node/pull/7831
943
description: The passed `options` object will never be modified.
944
- version: v5.0.0
945
pr-url: https://github.com/nodejs/node/pull/3163
946
description: The `file` parameter can be a file descriptor now.
947
-->
948
949
* `path` {string|Buffer|URL|number} filename or file descriptor
950
* `data` {string|Buffer}
951
* `options` {Object|string}
952
* `encoding` {string|null} **Default:** `'utf8'`
953
* `mode` {integer} **Default:** `0o666`
954
* `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
955
* `callback` {Function}
956
* `err` {Error}
957
958
Asynchronously append data to a file, creating the file if it does not yet
959
exist. `data` can be a string or a [`Buffer`][].
960
961
Example:
962
963
```js
964
fs.appendFile('message.txt', 'data to append', (err) => {
965
if (err) throw err;
966
console.log('The "data to append" was appended to file!');
967
});
968
```
969
970
If `options` is a string, then it specifies the encoding. Example:
971
972
```js
973
fs.appendFile('message.txt', 'data to append', 'utf8', callback);
974
```
975
976
The `path` may be specified as a numeric file descriptor that has been opened
977
for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
978
not be closed automatically.
979
980
```js
981
fs.open('message.txt', 'a', (err, fd) => {
982
if (err) throw err;
983
fs.appendFile(fd, 'data to append', 'utf8', (err) => {
984
fs.close(fd, (err) => {
985
if (err) throw err;
986
});
987
if (err) throw err;
988
});
989
});
990
```
991
992
## fs.appendFileSync(path, data[, options])
993
<!-- YAML
994
added: v0.6.7
995
changes:
996
- version: v7.0.0
997
pr-url: https://github.com/nodejs/node/pull/7831
998
description: The passed `options` object will never be modified.
999
- version: v5.0.0
1000
pr-url: https://github.com/nodejs/node/pull/3163