• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# File system
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!--name=fs-->
8
9<!-- source_link=lib/fs.js -->
10
11The `fs` module enables interacting with the file system in a
12way modeled on standard POSIX functions.
13
14To use this module:
15
16```js
17const fs = require('fs');
18```
19
20All file system operations have synchronous, callback, and promise-based
21forms.
22
23## Synchronous example
24
25The synchronous form blocks the Node.js event loop and further JavaScript
26execution until the operation is complete. Exceptions are thrown immediately
27and can be handled using `try…catch`, or can be allowed to bubble up.
28
29```js
30const fs = require('fs');
31
32try {
33  fs.unlinkSync('/tmp/hello');
34  console.log('successfully deleted /tmp/hello');
35} catch (err) {
36  // handle the error
37}
38```
39
40## Callback example
41
42The callback form takes a completion callback function as its last
43argument and invokes the operation asynchronously. The arguments passed to
44the completion callback depend on the method, but the first argument is always
45reserved for an exception. If the operation is completed successfully, then
46the first argument is `null` or `undefined`.
47
48```js
49const fs = require('fs');
50
51fs.unlink('/tmp/hello', (err) => {
52  if (err) throw err;
53  console.log('successfully deleted /tmp/hello');
54});
55```
56
57## Promise example
58
59Promise-based operations return a `Promise` that is resolved when the
60asynchronous operation is complete.
61
62```js
63const fs = require('fs').promises;
64
65(async function(path) {
66  try {
67    await fs.unlink(path);
68    console.log(`successfully deleted ${path}`);
69  } catch (error) {
70    console.error('there was an error:', error.message);
71  }
72})('/tmp/hello');
73```
74
75## Ordering of callback and promise-based operations
76
77There is no guaranteed ordering when using either the callback or
78promise-based methods. For example, the following is prone to error
79because the `fs.stat()` operation might complete before the `fs.rename()`
80operation:
81
82```js
83fs.rename('/tmp/hello', '/tmp/world', (err) => {
84  if (err) throw err;
85  console.log('renamed complete');
86});
87fs.stat('/tmp/world', (err, stats) => {
88  if (err) throw err;
89  console.log(`stats: ${JSON.stringify(stats)}`);
90});
91```
92
93To correctly order the operations, move the `fs.stat()` call into the callback
94of the `fs.rename()` operation:
95
96```js
97fs.rename('/tmp/hello', '/tmp/world', (err) => {
98  if (err) throw err;
99  fs.stat('/tmp/world', (err, stats) => {
100    if (err) throw err;
101    console.log(`stats: ${JSON.stringify(stats)}`);
102  });
103});
104```
105
106Or, use the promise-based API:
107
108```js
109const fs = require('fs').promises;
110
111(async function(from, to) {
112  try {
113    await fs.rename(from, to);
114    const stats = await fs.stat(to);
115    console.log(`stats: ${JSON.stringify(stats)}`);
116  } catch (error) {
117    console.error('there was an error:', error.message);
118  }
119})('/tmp/hello', '/tmp/world');
120```
121
122## File paths
123
124Most `fs` operations accept filepaths that may be specified in the form of
125a string, a [`Buffer`][], or a [`URL`][] object using the `file:` protocol.
126
127String form paths are interpreted as UTF-8 character sequences identifying
128the absolute or relative filename. Relative paths will be resolved relative
129to the current working directory as determined by calling `process.cwd()`.
130
131Example using an absolute path on POSIX:
132
133```js
134const fs = require('fs');
135
136fs.open('/open/some/file.txt', 'r', (err, fd) => {
137  if (err) throw err;
138  fs.close(fd, (err) => {
139    if (err) throw err;
140  });
141});
142```
143
144Example using a relative path on POSIX (relative to `process.cwd()`):
145
146```js
147fs.open('file.txt', 'r', (err, fd) => {
148  if (err) throw err;
149  fs.close(fd, (err) => {
150    if (err) throw err;
151  });
152});
153```
154
155Paths specified using a [`Buffer`][] are useful primarily on certain POSIX
156operating systems that treat file paths as opaque byte sequences. On such
157systems, it is possible for a single file path to contain sub-sequences that
158use multiple character encodings. As with string paths, `Buffer` paths may
159be relative or absolute:
160
161Example using an absolute path on POSIX:
162
163```js
164fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
165  if (err) throw err;
166  fs.close(fd, (err) => {
167    if (err) throw err;
168  });
169});
170```
171
172On Windows, Node.js follows the concept of per-drive working directory. This
173behavior can be observed when using a drive path without a backslash. For
174example `fs.readdirSync('C:\\')` can potentially return a different result than
175`fs.readdirSync('C:')`. For more information, see
176[this MSDN page][MSDN-Rel-Path].
177
178### URL object support
179<!-- YAML
180added: v7.6.0
181-->
182For most `fs` module functions, the `path` or `filename` argument may be passed
183as a WHATWG [`URL`][] object. Only [`URL`][] objects using the `file:` protocol
184are supported.
185
186```js
187const fs = require('fs');
188const fileUrl = new URL('file:///tmp/hello');
189
190fs.readFileSync(fileUrl);
191```
192
193`file:` URLs are always absolute paths.
194
195Using WHATWG [`URL`][] objects might introduce platform-specific behaviors.
196
197On Windows, `file:` URLs with a host name convert to UNC paths, while `file:`
198URLs with drive letters convert to local absolute paths. `file:` URLs without a
199host name nor a drive letter will result in a throw:
200
201```js
202// On Windows :
203
204// - WHATWG file URLs with hostname convert to UNC path
205// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
206fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
207
208// - WHATWG file URLs with drive letters convert to absolute path
209// file:///C:/tmp/hello => C:\tmp\hello
210fs.readFileSync(new URL('file:///C:/tmp/hello'));
211
212// - WHATWG file URLs without hostname must have a drive letters
213fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
214fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
215// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
216```
217
218`file:` URLs with drive letters must use `:` as a separator just after
219the drive letter. Using another separator will result in a throw.
220
221On all other platforms, `file:` URLs with a host name are unsupported and will
222result in a throw:
223
224```js
225// On other platforms:
226
227// - WHATWG file URLs with hostname are unsupported
228// file://hostname/p/a/t/h/file => throw!
229fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
230// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
231
232// - WHATWG file URLs convert to absolute path
233// file:///tmp/hello => /tmp/hello
234fs.readFileSync(new URL('file:///tmp/hello'));
235```
236
237A `file:` URL having encoded slash characters will result in a throw on all
238platforms:
239
240```js
241// On Windows
242fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
243fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
244/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
245\ or / characters */
246
247// On POSIX
248fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
249fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
250/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
251/ characters */
252```
253
254On Windows, `file:` URLs having encoded backslash will result in a throw:
255
256```js
257// On Windows
258fs.readFileSync(new URL('file:///C:/path/%5C'));
259fs.readFileSync(new URL('file:///C:/path/%5c'));
260/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
261\ or / characters */
262```
263
264## File descriptors
265
266On POSIX systems, for every process, the kernel maintains a table of currently
267open files and resources. Each open file is assigned a simple numeric
268identifier called a *file descriptor*. At the system-level, all file system
269operations use these file descriptors to identify and track each specific
270file. Windows systems use a different but conceptually similar mechanism for
271tracking resources. To simplify things for users, Node.js abstracts away the
272specific differences between operating systems and assigns all open files a
273numeric file descriptor.
274
275The `fs.open()` method is used to allocate a new file descriptor. Once
276allocated, the file descriptor may be used to read data from, write data to,
277or request information about the file.
278
279```js
280fs.open('/open/some/file.txt', 'r', (err, fd) => {
281  if (err) throw err;
282  fs.fstat(fd, (err, stat) => {
283    if (err) throw err;
284    // use stat
285
286    // always close the file descriptor!
287    fs.close(fd, (err) => {
288      if (err) throw err;
289    });
290  });
291});
292```
293
294Most operating systems limit the number of file descriptors that may be open
295at any given time so it is critical to close the descriptor when operations
296are completed. Failure to do so will result in a memory leak that will
297eventually cause an application to crash.
298
299## Threadpool usage
300
301All file system APIs except `fs.FSWatcher()` and those that are explicitly
302synchronous use libuv's threadpool, which can have surprising and negative
303performance implications for some applications. See the
304[`UV_THREADPOOL_SIZE`][] documentation for more information.
305
306## Class: `fs.Dir`
307<!-- YAML
308added: v12.12.0
309-->
310
311A class representing a directory stream.
312
313Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or
314[`fsPromises.opendir()`][].
315
316```js
317const fs = require('fs');
318
319async function print(path) {
320  const dir = await fs.promises.opendir(path);
321  for await (const dirent of dir) {
322    console.log(dirent.name);
323  }
324}
325print('./').catch(console.error);
326```
327
328### `dir.close()`
329<!-- YAML
330added: v12.12.0
331-->
332
333* Returns: {Promise}
334
335Asynchronously close the directory's underlying resource handle.
336Subsequent reads will result in errors.
337
338A `Promise` is returned that will be resolved after the resource has been
339closed.
340
341### `dir.close(callback)`
342<!-- YAML
343added: v12.12.0
344-->
345
346* `callback` {Function}
347  * `err` {Error}
348
349Asynchronously close the directory's underlying resource handle.
350Subsequent reads will result in errors.
351
352The `callback` will be called after the resource handle has been closed.
353
354### `dir.closeSync()`
355<!-- YAML
356added: v12.12.0
357-->
358
359Synchronously close the directory's underlying resource handle.
360Subsequent reads will result in errors.
361
362### `dir.path`
363<!-- YAML
364added: v12.12.0
365-->
366
367* {string}
368
369The read-only path of this directory as was provided to [`fs.opendir()`][],
370[`fs.opendirSync()`][], or [`fsPromises.opendir()`][].
371
372### `dir.read()`
373<!-- YAML
374added: v12.12.0
375-->
376
377* Returns: {Promise} containing {fs.Dirent|null}
378
379Asynchronously read the next directory entry via readdir(3) as an
380[`fs.Dirent`][].
381
382After the read is completed, a `Promise` is returned that will be resolved with
383an [`fs.Dirent`][], or `null` if there are no more directory entries to read.
384
385Directory entries returned by this function are in no particular order as
386provided by the operating system's underlying directory mechanisms.
387Entries added or removed while iterating over the directory may or may not be
388included in the iteration results.
389
390### `dir.read(callback)`
391<!-- YAML
392added: v12.12.0
393-->
394
395* `callback` {Function}
396  * `err` {Error}
397  * `dirent` {fs.Dirent|null}
398
399Asynchronously read the next directory entry via readdir(3) as an
400[`fs.Dirent`][].
401
402After the read is completed, the `callback` will be called with an
403[`fs.Dirent`][], or `null` if there are no more directory entries to read.
404
405Directory entries returned by this function are in no particular order as
406provided by the operating system's underlying directory mechanisms.
407Entries added or removed while iterating over the directory may or may not be
408included in the iteration results.
409
410### `dir.readSync()`
411<!-- YAML
412added: v12.12.0
413-->
414
415* Returns: {fs.Dirent|null}
416
417Synchronously read the next directory entry via readdir(3) as an
418[`fs.Dirent`][].
419
420If there are no more directory entries to read, `null` will be returned.
421
422Directory entries returned by this function are in no particular order as
423provided by the operating system's underlying directory mechanisms.
424Entries added or removed while iterating over the directory may or may not be
425included in the iteration results.
426
427### `dir[Symbol.asyncIterator]()`
428<!-- YAML
429added: v12.12.0
430-->
431
432* Returns: {AsyncIterator} of {fs.Dirent}
433
434Asynchronously iterates over the directory via readdir(3) until all entries have
435been read.
436
437Entries returned by the async iterator are always an [`fs.Dirent`][].
438The `null` case from `dir.read()` is handled internally.
439
440See [`fs.Dir`][] for an example.
441
442Directory entries returned by this iterator are in no particular order as
443provided by the operating system's underlying directory mechanisms.
444Entries added or removed while iterating over the directory may or may not be
445included in the iteration results.
446
447## Class: `fs.Dirent`
448<!-- YAML
449added: v10.10.0
450-->
451
452A representation of a directory entry, which can be a file or a subdirectory
453within the directory, as returned by reading from an [`fs.Dir`][]. The
454directory entry is a combination of the file name and file type pairs.
455
456Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with
457the `withFileTypes` option set to `true`, the resulting array is filled with
458`fs.Dirent` objects, rather than strings or `Buffers`.
459
460### `dirent.isBlockDevice()`
461<!-- YAML
462added: v10.10.0
463-->
464
465* Returns: {boolean}
466
467Returns `true` if the `fs.Dirent` object describes a block device.
468
469### `dirent.isCharacterDevice()`
470<!-- YAML
471added: v10.10.0
472-->
473
474* Returns: {boolean}
475
476Returns `true` if the `fs.Dirent` object describes a character device.
477
478### `dirent.isDirectory()`
479<!-- YAML
480added: v10.10.0
481-->
482
483* Returns: {boolean}
484
485Returns `true` if the `fs.Dirent` object describes a file system
486directory.
487
488### `dirent.isFIFO()`
489<!-- YAML
490added: v10.10.0
491-->
492
493* Returns: {boolean}
494
495Returns `true` if the `fs.Dirent` object describes a first-in-first-out
496(FIFO) pipe.
497
498### `dirent.isFile()`
499<!-- YAML
500added: v10.10.0
501-->
502
503* Returns: {boolean}
504
505Returns `true` if the `fs.Dirent` object describes a regular file.
506
507### `dirent.isSocket()`
508<!-- YAML
509added: v10.10.0
510-->
511
512* Returns: {boolean}
513
514Returns `true` if the `fs.Dirent` object describes a socket.
515
516### `dirent.isSymbolicLink()`
517<!-- YAML
518added: v10.10.0
519-->
520
521* Returns: {boolean}
522
523Returns `true` if the `fs.Dirent` object describes a symbolic link.
524
525### `dirent.name`
526<!-- YAML
527added: v10.10.0
528-->
529
530* {string|Buffer}
531
532The file name that this `fs.Dirent` object refers to. The type of this
533value is determined by the `options.encoding` passed to [`fs.readdir()`][] or
534[`fs.readdirSync()`][].
535
536## Class: `fs.FSWatcher`
537<!-- YAML
538added: v0.5.8
539-->
540
541* Extends {EventEmitter}
542
543A successful call to [`fs.watch()`][] method will return a new `fs.FSWatcher`
544object.
545
546All `fs.FSWatcher` objects emit a `'change'` event whenever a specific watched
547file is modified.
548
549### Event: `'change'`
550<!-- YAML
551added: v0.5.8
552-->
553
554* `eventType` {string} The type of change event that has occurred
555* `filename` {string|Buffer} The filename that changed (if relevant/available)
556
557Emitted when something changes in a watched directory or file.
558See more details in [`fs.watch()`][].
559
560The `filename` argument may not be provided depending on operating system
561support. If `filename` is provided, it will be provided as a `Buffer` if
562`fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise
563`filename` will be a UTF-8 string.
564
565```js
566// Example when handled through fs.watch() listener
567fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
568  if (filename) {
569    console.log(filename);
570    // Prints: <Buffer ...>
571  }
572});
573```
574
575### Event: `'close'`
576<!-- YAML
577added: v10.0.0
578-->
579
580Emitted when the watcher stops watching for changes. The closed
581`fs.FSWatcher` object is no longer usable in the event handler.
582
583### Event: `'error'`
584<!-- YAML
585added: v0.5.8
586-->
587
588* `error` {Error}
589
590Emitted when an error occurs while watching the file. The errored
591`fs.FSWatcher` object is no longer usable in the event handler.
592
593### `watcher.close()`
594<!-- YAML
595added: v0.5.8
596-->
597
598Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the
599`fs.FSWatcher` object is no longer usable.
600
601### `watcher.ref()`
602<!-- YAML
603added: v12.20.0
604-->
605
606* Returns: {fs.FSWatcher}
607
608When called, requests that the Node.js event loop *not* exit so long as the
609`FSWatcher` is active. Calling `watcher.ref()` multiple times will have
610no effect.
611
612By default, all `FSWatcher` objects are "ref'ed", making it normally
613unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
614called previously.
615
616### `watcher.unref()`
617<!-- YAML
618added: v12.20.0
619-->
620
621* Returns: {fs.FSWatcher}
622
623When called, the active `FSWatcher` object will not require the Node.js
624event loop to remain active. If there is no other activity keeping the
625event loop running, the process may exit before the `FSWatcher` object's
626callback is invoked. Calling `watcher.unref()` multiple times will have
627no effect.
628
629## Class: `fs.StatWatcher`
630<!-- YAML
631added: v12.20.0
632-->
633
634* Extends {EventEmitter}
635
636A successful call to `fs.watchFile()` method will return a new `fs.StatWatcher`
637object.
638
639### `watcher.ref()`
640<!-- YAML
641added: v12.20.0
642-->
643
644* Returns: {fs.StatWatcher}
645
646When called, requests that the Node.js event loop *not* exit so long as the
647`StatWatcher` is active. Calling `watcher.ref()` multiple times will have
648no effect.
649
650By default, all `StatWatcher` objects are "ref'ed", making it normally
651unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
652called previously.
653
654### `watcher.unref()`
655<!-- YAML
656added: v12.20.0
657-->
658
659* Returns: {fs.StatWatcher}
660
661When called, the active `StatWatcher` object will not require the Node.js
662event loop to remain active. If there is no other activity keeping the
663event loop running, the process may exit before the `StatWatcher` object's
664callback is invoked. Calling `watcher.unref()` multiple times will have
665no effect.
666
667## Class: `fs.ReadStream`
668<!-- YAML
669added: v0.1.93
670-->
671
672* Extends: {stream.Readable}
673
674Instances of `fs.ReadStream` are created and returned using the
675[`fs.createReadStream()`][] function.
676
677### Event: `'close'`
678<!-- YAML
679added: v0.1.93
680-->
681
682Emitted when the `fs.ReadStream`'s underlying file descriptor has been closed.
683
684### Event: `'open'`
685<!-- YAML
686added: v0.1.93
687-->
688
689* `fd` {integer} Integer file descriptor used by the `ReadStream`.
690
691Emitted when the `fs.ReadStream`'s file descriptor has been opened.
692
693### Event: `'ready'`
694<!-- YAML
695added: v9.11.0
696-->
697
698Emitted when the `fs.ReadStream` is ready to be used.
699
700Fires immediately after `'open'`.
701
702### `readStream.bytesRead`
703<!-- YAML
704added: v6.4.0
705-->
706
707* {number}
708
709The number of bytes that have been read so far.
710
711### `readStream.path`
712<!-- YAML
713added: v0.1.93
714-->
715
716* {string|Buffer}
717
718The path to the file the stream is reading from as specified in the first
719argument to `fs.createReadStream()`. If `path` is passed as a string, then
720`readStream.path` will be a string. If `path` is passed as a `Buffer`, then
721`readStream.path` will be a `Buffer`.
722
723### `readStream.pending`
724<!-- YAML
725added: v11.2.0
726-->
727
728* {boolean}
729
730This property is `true` if the underlying file has not been opened yet,
731i.e. before the `'ready'` event is emitted.
732
733## Class: `fs.Stats`
734<!-- YAML
735added: v0.1.21
736changes:
737  - version: v8.1.0
738    pr-url: https://github.com/nodejs/node/pull/13173
739    description: Added times as numbers.
740-->
741
742A `fs.Stats` object provides information about a file.
743
744Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and
745their synchronous counterparts are of this type.
746If `bigint` in the `options` passed to those methods is true, the numeric values
747will be `bigint` instead of `number`, and the object will contain additional
748nanosecond-precision properties suffixed with `Ns`.
749
750```console
751Stats {
752  dev: 2114,
753  ino: 48064969,
754  mode: 33188,
755  nlink: 1,
756  uid: 85,
757  gid: 100,
758  rdev: 0,
759  size: 527,
760  blksize: 4096,
761  blocks: 8,
762  atimeMs: 1318289051000.1,
763  mtimeMs: 1318289051000.1,
764  ctimeMs: 1318289051000.1,
765  birthtimeMs: 1318289051000.1,
766  atime: Mon, 10 Oct 2011 23:24:11 GMT,
767  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
768  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
769  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
770```
771
772`bigint` version:
773
774```console
775BigIntStats {
776  dev: 2114n,
777  ino: 48064969n,
778  mode: 33188n,
779  nlink: 1n,
780  uid: 85n,
781  gid: 100n,
782  rdev: 0n,
783  size: 527n,
784  blksize: 4096n,
785  blocks: 8n,
786  atimeMs: 1318289051000n,
787  mtimeMs: 1318289051000n,
788  ctimeMs: 1318289051000n,
789  birthtimeMs: 1318289051000n,
790  atimeNs: 1318289051000000000n,
791  mtimeNs: 1318289051000000000n,
792  ctimeNs: 1318289051000000000n,
793  birthtimeNs: 1318289051000000000n,
794  atime: Mon, 10 Oct 2011 23:24:11 GMT,
795  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
796  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
797  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
798```
799
800### `stats.isBlockDevice()`
801<!-- YAML
802added: v0.1.10
803-->
804
805* Returns: {boolean}
806
807Returns `true` if the `fs.Stats` object describes a block device.
808
809### `stats.isCharacterDevice()`
810<!-- YAML
811added: v0.1.10
812-->
813
814* Returns: {boolean}
815
816Returns `true` if the `fs.Stats` object describes a character device.
817
818### `stats.isDirectory()`
819<!-- YAML
820added: v0.1.10
821-->
822
823* Returns: {boolean}
824
825Returns `true` if the `fs.Stats` object describes a file system directory.
826
827### `stats.isFIFO()`
828<!-- YAML
829added: v0.1.10
830-->
831
832* Returns: {boolean}
833
834Returns `true` if the `fs.Stats` object describes a first-in-first-out (FIFO)
835pipe.
836
837### `stats.isFile()`
838<!-- YAML
839added: v0.1.10
840-->
841
842* Returns: {boolean}
843
844Returns `true` if the `fs.Stats` object describes a regular file.
845
846### `stats.isSocket()`
847<!-- YAML
848added: v0.1.10
849-->
850
851* Returns: {boolean}
852
853Returns `true` if the `fs.Stats` object describes a socket.
854
855### `stats.isSymbolicLink()`
856<!-- YAML
857added: v0.1.10
858-->
859
860* Returns: {boolean}
861
862Returns `true` if the `fs.Stats` object describes a symbolic link.
863
864This method is only valid when using [`fs.lstat()`][].
865
866### `stats.dev`
867
868* {number|bigint}
869
870The numeric identifier of the device containing the file.
871
872### `stats.ino`
873
874* {number|bigint}
875
876The file system specific "Inode" number for the file.
877
878### `stats.mode`
879
880* {number|bigint}
881
882A bit-field describing the file type and mode.
883
884### `stats.nlink`
885
886* {number|bigint}
887
888The number of hard-links that exist for the file.
889
890### `stats.uid`
891
892* {number|bigint}
893
894The numeric user identifier of the user that owns the file (POSIX).
895
896### `stats.gid`
897
898* {number|bigint}
899
900The numeric group identifier of the group that owns the file (POSIX).
901
902### `stats.rdev`
903
904* {number|bigint}
905
906A numeric device identifier if the file represents a device.
907
908### `stats.size`
909
910* {number|bigint}
911
912The size of the file in bytes.
913
914### `stats.blksize`
915
916* {number|bigint}
917
918The file system block size for i/o operations.
919
920### `stats.blocks`
921
922* {number|bigint}
923
924The number of blocks allocated for this file.
925
926### `stats.atimeMs`
927<!-- YAML
928added: v8.1.0
929-->
930
931* {number|bigint}
932
933The timestamp indicating the last time this file was accessed expressed in
934milliseconds since the POSIX Epoch.
935
936### `stats.mtimeMs`
937<!-- YAML
938added: v8.1.0
939-->
940
941* {number|bigint}
942
943The timestamp indicating the last time this file was modified expressed in
944milliseconds since the POSIX Epoch.
945
946### `stats.ctimeMs`
947<!-- YAML
948added: v8.1.0
949-->
950
951* {number|bigint}
952
953The timestamp indicating the last time the file status was changed expressed
954in milliseconds since the POSIX Epoch.
955
956### `stats.birthtimeMs`
957<!-- YAML
958added: v8.1.0
959-->
960
961* {number|bigint}
962
963The timestamp indicating the creation time of this file expressed in
964milliseconds since the POSIX Epoch.
965
966### `stats.atimeNs`
967<!-- YAML
968added: v12.10.0
969-->
970
971* {bigint}
972
973Only present when `bigint: true` is passed into the method that generates
974the object.
975The timestamp indicating the last time this file was accessed expressed in
976nanoseconds since the POSIX Epoch.
977
978### `stats.mtimeNs`
979<!-- YAML
980added: v12.10.0
981-->
982
983* {bigint}
984
985Only present when `bigint: true` is passed into the method that generates
986the object.
987The timestamp indicating the last time this file was modified expressed in
988nanoseconds since the POSIX Epoch.
989
990### `stats.ctimeNs`
991<!-- YAML
992added: v12.10.0
993-->
994
995* {bigint}
996
997Only present when `bigint: true` is passed into the method that generates
998the object.
999The timestamp indicating the last time the file status was changed expressed
1000in nanoseconds since the POSIX Epoch.
1001
1002### `stats.birthtimeNs`
1003<!-- YAML
1004added: v12.10.0
1005-->
1006
1007* {bigint}
1008
1009Only present when `bigint: true` is passed into the method that generates
1010the object.
1011The timestamp indicating the creation time of this file expressed in
1012nanoseconds since the POSIX Epoch.
1013
1014### `stats.atime`
1015<!-- YAML
1016added: v0.11.13
1017-->
1018
1019* {Date}
1020
1021The timestamp indicating the last time this file was accessed.
1022
1023### `stats.mtime`
1024<!-- YAML
1025added: v0.11.13
1026-->
1027
1028* {Date}
1029
1030The timestamp indicating the last time this file was modified.
1031
1032### `stats.ctime`
1033<!-- YAML
1034added: v0.11.13
1035-->
1036
1037* {Date}
1038
1039The timestamp indicating the last time the file status was changed.
1040
1041### `stats.birthtime`
1042<!-- YAML
1043added: v0.11.13
1044-->
1045
1046* {Date}
1047
1048The timestamp indicating the creation time of this file.
1049
1050### Stat time values
1051
1052The `atimeMs`, `mtimeMs`, `ctimeMs`, `birthtimeMs` properties are
1053numeric values that hold the corresponding times in milliseconds. Their
1054precision is platform specific. When `bigint: true` is passed into the
1055method that generates the object, the properties will be [bigints][],
1056otherwise they will be [numbers][MDN-Number].
1057
1058The `atimeNs`, `mtimeNs`, `ctimeNs`, `birthtimeNs` properties are
1059[bigints][] that hold the corresponding times in nanoseconds. They are
1060only present when `bigint: true` is passed into the method that generates
1061the object. Their precision is platform specific.
1062
1063`atime`, `mtime`, `ctime`, and `birthtime` are
1064[`Date`][MDN-Date] object alternate representations of the various times. The
1065`Date` and number values are not connected. Assigning a new number value, or
1066mutating the `Date` value, will not be reflected in the corresponding alternate
1067representation.
1068
1069The times in the stat object have the following semantics:
1070
1071* `atime` "Access Time": Time when file data last accessed. Changed
1072  by the mknod(2), utimes(2), and read(2) system calls.
1073* `mtime` "Modified Time": Time when file data last modified.
1074  Changed by the mknod(2), utimes(2), and write(2) system calls.
1075* `ctime` "Change Time": Time when file status was last changed
1076  (inode data modification). Changed by the chmod(2), chown(2),
1077  link(2), mknod(2), rename(2), unlink(2), utimes(2),
1078  read(2), and write(2) system calls.
1079* `birthtime` "Birth Time": Time of file creation. Set once when the
1080  file is created. On filesystems where birthtime is not available,
1081  this field may instead hold either the `ctime` or
1082  `1970-01-01T00:00Z` (ie, Unix epoch timestamp `0`). This value may be greater
1083  than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants,
1084  also set if the `atime` is explicitly set to an earlier value than the current
1085  `birthtime` using the utimes(2) system call.
1086
1087Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As
1088of 0.12, `ctime` is not "creation time", and on Unix systems, it never was.
1089
1090## Class: `fs.WriteStream`
1091<!-- YAML
1092added: v0.1.93
1093-->
1094
1095* Extends {stream.Writable}
1096
1097Instances of `fs.WriteStream` are created and returned using the
1098[`fs.createWriteStream()`][] function.
1099
1100### Event: `'close'`
1101<!-- YAML
1102added: v0.1.93
1103-->
1104
1105Emitted when the `WriteStream`'s underlying file descriptor has been closed.
1106
1107### Event: `'open'`
1108<!-- YAML
1109added: v0.1.93
1110-->
1111
1112* `fd` {integer} Integer file descriptor used by the `WriteStream`.
1113
1114Emitted when the `WriteStream`'s file is opened.
1115
1116### Event: `'ready'`
1117<!-- YAML
1118added: v9.11.0
1119-->
1120
1121Emitted when the `fs.WriteStream` is ready to be used.
1122
1123Fires immediately after `'open'`.
1124
1125### `writeStream.bytesWritten`
1126<!-- YAML
1127added: v0.4.7
1128-->
1129
1130The number of bytes written so far. Does not include data that is still queued
1131for writing.
1132
1133### `writeStream.path`
1134<!-- YAML
1135added: v0.1.93
1136-->
1137
1138The path to the file the stream is writing to as specified in the first
1139argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then
1140`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then
1141`writeStream.path` will be a `Buffer`.
1142
1143### `writeStream.pending`
1144<!-- YAML
1145added: v11.2.0
1146-->
1147
1148* {boolean}
1149
1150This property is `true` if the underlying file has not been opened yet,
1151i.e. before the `'ready'` event is emitted.
1152
1153## `fs.access(path[, mode], callback)`
1154<!-- YAML
1155added: v0.11.15
1156changes:
1157  - version: v7.6.0
1158    pr-url: https://github.com/nodejs/node/pull/10739
1159    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1160                 protocol. Support is currently still *experimental*.
1161  - version: v6.3.0
1162    pr-url: https://github.com/nodejs/node/pull/6534
1163    description: The constants like `fs.R_OK`, etc which were present directly
1164                 on `fs` were moved into `fs.constants` as a soft deprecation.
1165                 Thus for Node.js `< v6.3.0` use `fs`
1166                 to access those constants, or
1167                 do something like `(fs.constants || fs).R_OK` to work with all
1168                 versions.
1169-->
1170
1171* `path` {string|Buffer|URL}
1172* `mode` {integer} **Default:** `fs.constants.F_OK`
1173* `callback` {Function}
1174  * `err` {Error}
1175
1176Tests a user's permissions for the file or directory specified by `path`.
1177The `mode` argument is an optional integer that specifies the accessibility
1178checks to be performed. Check [File access constants][] for possible values
1179of `mode`. It is possible to create a mask consisting of the bitwise OR of
1180two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
1181
1182The final argument, `callback`, is a callback function that is invoked with
1183a possible error argument. If any of the accessibility checks fail, the error
1184argument will be an `Error` object. The following examples check if
1185`package.json` exists, and if it is readable or writable.
1186
1187```js
1188const file = 'package.json';
1189
1190// Check if the file exists in the current directory.
1191fs.access(file, fs.constants.F_OK, (err) => {
1192  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
1193});
1194
1195// Check if the file is readable.
1196fs.access(file, fs.constants.R_OK, (err) => {
1197  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
1198});
1199
1200// Check if the file is writable.
1201fs.access(file, fs.constants.W_OK, (err) => {
1202  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
1203});
1204
1205// Check if the file exists in the current directory, and if it is writable.
1206fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
1207  if (err) {
1208    console.error(
1209      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
1210  } else {
1211    console.log(`${file} exists, and it is writable`);
1212  }
1213});
1214```
1215
1216Do not use `fs.access()` to check for the accessibility of a file before calling
1217`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing
1218so introduces a race condition, since other processes may change the file's
1219state between the two calls. Instead, user code should open/read/write the
1220file directly and handle the error raised if the file is not accessible.
1221
1222**write (NOT RECOMMENDED)**
1223
1224```js
1225fs.access('myfile', (err) => {
1226  if (!err) {
1227    console.error('myfile already exists');
1228    return;
1229  }
1230
1231  fs.open('myfile', 'wx', (err, fd) => {
1232    if (err) throw err;
1233    writeMyData(fd);
1234  });
1235});
1236```
1237
1238**write (RECOMMENDED)**
1239
1240```js
1241fs.open('myfile', 'wx', (err, fd) => {
1242  if (err) {
1243    if (err.code === 'EEXIST') {
1244      console.error('myfile already exists');
1245      return;
1246    }
1247
1248    throw err;
1249  }
1250
1251  writeMyData(fd);
1252});
1253```
1254
1255**read (NOT RECOMMENDED)**
1256
1257```js
1258fs.access('myfile', (err) => {
1259  if (err) {
1260    if (err.code === 'ENOENT') {
1261      console.error('myfile does not exist');
1262      return;
1263    }
1264
1265    throw err;
1266  }
1267
1268  fs.open('myfile', 'r', (err, fd) => {
1269    if (err) throw err;
1270    readMyData(fd);
1271  });
1272});
1273```
1274
1275**read (RECOMMENDED)**
1276
1277```js
1278fs.open('myfile', 'r', (err, fd) => {
1279  if (err) {
1280    if (err.code === 'ENOENT') {
1281      console.error('myfile does not exist');
1282      return;
1283    }
1284
1285    throw err;
1286  }
1287
1288  readMyData(fd);
1289});
1290```
1291
1292The "not recommended" examples above check for accessibility and then use the
1293file; the "recommended" examples are better because they use the file directly
1294and handle the error, if any.
1295
1296In general, check for the accessibility of a file only if the file will not be
1297used directly, for example when its accessibility is a signal from another
1298process.
1299
1300On Windows, access-control policies (ACLs) on a directory may limit access to
1301a file or directory. The `fs.access()` function, however, does not check the
1302ACL and therefore may report that a path is accessible even if the ACL restricts
1303the user from reading or writing to it.
1304
1305## `fs.accessSync(path[, mode])`
1306<!-- YAML
1307added: v0.11.15
1308changes:
1309  - version: v7.6.0
1310    pr-url: https://github.com/nodejs/node/pull/10739
1311    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1312                 protocol. Support is currently still *experimental*.
1313-->
1314
1315* `path` {string|Buffer|URL}
1316* `mode` {integer} **Default:** `fs.constants.F_OK`
1317
1318Synchronously tests a user's permissions for the file or directory specified
1319by `path`. The `mode` argument is an optional integer that specifies the
1320accessibility checks to be performed. Check [File access constants][] for
1321possible values of `mode`. It is possible to create a mask consisting of
1322the bitwise OR of two or more values
1323(e.g. `fs.constants.W_OK | fs.constants.R_OK`).
1324
1325If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
1326the method will return `undefined`.
1327
1328```js
1329try {
1330  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
1331  console.log('can read/write');
1332} catch (err) {
1333  console.error('no access!');
1334}
1335```
1336
1337## `fs.appendFile(path, data[, options], callback)`
1338<!-- YAML
1339added: v0.6.7
1340changes:
1341  - version: v10.0.0
1342    pr-url: https://github.com/nodejs/node/pull/12562
1343    description: The `callback` parameter is no longer optional. Not passing
1344                 it will throw a `TypeError` at runtime.
1345  - version: v7.0.0
1346    pr-url: https://github.com/nodejs/node/pull/7897
1347    description: The `callback` parameter is no longer optional. Not passing
1348                 it will emit a deprecation warning with id DEP0013.
1349  - version: v7.0.0
1350    pr-url: https://github.com/nodejs/node/pull/7831
1351    description: The passed `options` object will never be modified.
1352  - version: v5.0.0
1353    pr-url: https://github.com/nodejs/node/pull/3163
1354    description: The `file` parameter can be a file descriptor now.
1355-->
1356
1357* `path` {string|Buffer|URL|number} filename or file descriptor
1358* `data` {string|Buffer}
1359* `options` {Object|string}
1360  * `encoding` {string|null} **Default:** `'utf8'`
1361  * `mode` {integer} **Default:** `0o666`
1362  * `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
1363* `callback` {Function}
1364  * `err` {Error}
1365
1366Asynchronously append data to a file, creating the file if it does not yet
1367exist. `data` can be a string or a [`Buffer`][].
1368
1369```js
1370fs.appendFile('message.txt', 'data to append', (err) => {
1371  if (err) throw err;
1372  console.log('The "data to append" was appended to file!');
1373});
1374```
1375
1376If `options` is a string, then it specifies the encoding:
1377
1378```js
1379fs.appendFile('message.txt', 'data to append', 'utf8', callback);
1380```
1381
1382The `path` may be specified as a numeric file descriptor that has been opened
1383for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
1384not be closed automatically.
1385
1386```js
1387fs.open('message.txt', 'a', (err, fd) => {
1388  if (err) throw err;
1389  fs.appendFile(fd, 'data to append', 'utf8', (err) => {
1390    fs.close(fd, (err) => {
1391      if (err) throw err;
1392    });
1393    if (err) throw err;
1394  });
1395});
1396```
1397
1398## `fs.appendFileSync(path, data[, options])`
1399<!-- YAML
1400added: v0.6.7
1401changes:
1402  - version: v7.0.0
1403    pr-url: https://github.com/nodejs/node/pull/7831
1404    description: The passed `options` object will never be modified.
1405  - version: v5.0.0
1406    pr-url: https://github.com/nodejs/node/pull/3163
1407    description: The `file` parameter can be a file descriptor now.
1408-->
1409
1410* `path` {string|Buffer|URL|number} filename or file descriptor
1411* `data` {string|Buffer}
1412* `options` {Object|string}
1413  * `encoding` {string|null} **Default:** `'utf8'`
1414  * `mode` {integer} **Default:** `0o666`
1415  * `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
1416
1417Synchronously append data to a file, creating the file if it does not yet
1418exist. `data` can be a string or a [`Buffer`][].
1419
1420```js
1421try {
1422  fs.appendFileSync('message.txt', 'data to append');
1423  console.log('The "data to append" was appended to file!');
1424} catch (err) {
1425  /* Handle the error */
1426}
1427```
1428
1429If `options` is a string, then it specifies the encoding:
1430
1431```js
1432fs.appendFileSync('message.txt', 'data to append', 'utf8');
1433```
1434
1435The `path` may be specified as a numeric file descriptor that has been opened
1436for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
1437not be closed automatically.
1438
1439```js
1440let fd;
1441
1442try {
1443  fd = fs.openSync('message.txt', 'a');
1444  fs.appendFileSync(fd, 'data to append', 'utf8');
1445} catch (err) {
1446  /* Handle the error */
1447} finally {
1448  if (fd !== undefined)
1449    fs.closeSync(fd);
1450}
1451```
1452
1453## `fs.chmod(path, mode, callback)`
1454<!-- YAML
1455added: v0.1.30
1456changes:
1457  - version: v10.0.0
1458    pr-url: https://github.com/nodejs/node/pull/12562
1459    description: The `callback` parameter is no longer optional. Not passing
1460                 it will throw a `TypeError` at runtime.
1461  - version: v7.6.0
1462    pr-url: https://github.com/nodejs/node/pull/10739
1463    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1464                 protocol. Support is currently still *experimental*.
1465  - version: v7.0.0
1466    pr-url: https://github.com/nodejs/node/pull/7897
1467    description: The `callback` parameter is no longer optional. Not passing
1468                 it will emit a deprecation warning with id DEP0013.
1469-->
1470
1471* `path` {string|Buffer|URL}
1472* `mode` {string|integer}
1473* `callback` {Function}
1474  * `err` {Error}
1475
1476Asynchronously changes the permissions of a file. No arguments other than a
1477possible exception are given to the completion callback.
1478
1479See also: chmod(2).
1480
1481```js
1482fs.chmod('my_file.txt', 0o775, (err) => {
1483  if (err) throw err;
1484  console.log('The permissions for file "my_file.txt" have been changed!');
1485});
1486```
1487
1488### File modes
1489
1490The `mode` argument used in both the `fs.chmod()` and `fs.chmodSync()`
1491methods is a numeric bitmask created using a logical OR of the following
1492constants:
1493
1494|       Constant         |  Octal  | Description              |
1495| ---------------------- | ------- | ------------------------ |
1496| `fs.constants.S_IRUSR` | `0o400` | read by owner            |
1497| `fs.constants.S_IWUSR` | `0o200` | write by owner           |
1498| `fs.constants.S_IXUSR` | `0o100` | execute/search by owner  |
1499| `fs.constants.S_IRGRP` | `0o40`  | read by group            |
1500| `fs.constants.S_IWGRP` | `0o20`  | write by group           |
1501| `fs.constants.S_IXGRP` | `0o10`  | execute/search by group  |
1502| `fs.constants.S_IROTH` | `0o4`   | read by others           |
1503| `fs.constants.S_IWOTH` | `0o2`   | write by others          |
1504| `fs.constants.S_IXOTH` | `0o1`   | execute/search by others |
1505
1506An easier method of constructing the `mode` is to use a sequence of three
1507octal digits (e.g. `765`). The left-most digit (`7` in the example), specifies
1508the permissions for the file owner. The middle digit (`6` in the example),
1509specifies permissions for the group. The right-most digit (`5` in the example),
1510specifies the permissions for others.
1511
1512| Number  |       Description        |
1513| ------- | ------------------------ |
1514|   `7`   | read, write, and execute |
1515|   `6`   | read and write           |
1516|   `5`   | read and execute         |
1517|   `4`   | read only                |
1518|   `3`   | write and execute        |
1519|   `2`   | write only               |
1520|   `1`   | execute only             |
1521|   `0`   | no permission            |
1522
1523For example, the octal value `0o765` means:
1524
1525* The owner may read, write and execute the file.
1526* The group may read and write the file.
1527* Others may read and execute the file.
1528
1529When using raw numbers where file modes are expected, any value larger than
1530`0o777` may result in platform-specific behaviors that are not supported to work
1531consistently. Therefore constants like `S_ISVTX`, `S_ISGID` or `S_ISUID` are not
1532exposed in `fs.constants`.
1533
1534Caveats: on Windows only the write permission can be changed, and the
1535distinction among the permissions of group, owner or others is not
1536implemented.
1537
1538## `fs.chmodSync(path, mode)`
1539<!-- YAML
1540added: v0.6.7
1541changes:
1542  - version: v7.6.0
1543    pr-url: https://github.com/nodejs/node/pull/10739
1544    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1545                 protocol. Support is currently still *experimental*.
1546-->
1547
1548* `path` {string|Buffer|URL}
1549* `mode` {string|integer}
1550
1551For detailed information, see the documentation of the asynchronous version of
1552this API: [`fs.chmod()`][].
1553
1554See also: chmod(2).
1555
1556## `fs.chown(path, uid, gid, callback)`
1557<!-- YAML
1558added: v0.1.97
1559changes:
1560  - version: v10.0.0
1561    pr-url: https://github.com/nodejs/node/pull/12562
1562    description: The `callback` parameter is no longer optional. Not passing
1563                 it will throw a `TypeError` at runtime.
1564  - version: v7.6.0
1565    pr-url: https://github.com/nodejs/node/pull/10739
1566    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1567                 protocol. Support is currently still *experimental*.
1568  - version: v7.0.0
1569    pr-url: https://github.com/nodejs/node/pull/7897
1570    description: The `callback` parameter is no longer optional. Not passing
1571                 it will emit a deprecation warning with id DEP0013.
1572-->
1573
1574* `path` {string|Buffer|URL}
1575* `uid` {integer}
1576* `gid` {integer}
1577* `callback` {Function}
1578  * `err` {Error}
1579
1580Asynchronously changes owner and group of a file. No arguments other than a
1581possible exception are given to the completion callback.
1582
1583See also: chown(2).
1584
1585## `fs.chownSync(path, uid, gid)`
1586<!-- YAML
1587added: v0.1.97
1588changes:
1589  - version: v7.6.0
1590    pr-url: https://github.com/nodejs/node/pull/10739
1591    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1592                 protocol. Support is currently still *experimental*.
1593-->
1594
1595* `path` {string|Buffer|URL}
1596* `uid` {integer}
1597* `gid` {integer}
1598
1599Synchronously changes owner and group of a file. Returns `undefined`.
1600This is the synchronous version of [`fs.chown()`][].
1601
1602See also: chown(2).
1603
1604## `fs.close(fd, callback)`
1605<!-- YAML
1606added: v0.0.2
1607changes:
1608  - version: v10.0.0
1609    pr-url: https://github.com/nodejs/node/pull/12562
1610    description: The `callback` parameter is no longer optional. Not passing
1611                 it will throw a `TypeError` at runtime.
1612  - version: v7.0.0
1613    pr-url: https://github.com/nodejs/node/pull/7897
1614    description: The `callback` parameter is no longer optional. Not passing
1615                 it will emit a deprecation warning with id DEP0013.
1616-->
1617
1618* `fd` {integer}
1619* `callback` {Function}
1620  * `err` {Error}
1621
1622Asynchronous close(2). No arguments other than a possible exception are given
1623to the completion callback.
1624
1625Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
1626through any other `fs` operation may lead to undefined behavior.
1627
1628## `fs.closeSync(fd)`
1629<!-- YAML
1630added: v0.1.21
1631-->
1632
1633* `fd` {integer}
1634
1635Synchronous close(2). Returns `undefined`.
1636
1637Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use
1638through any other `fs` operation may lead to undefined behavior.
1639
1640## `fs.constants`
1641
1642* {Object}
1643
1644Returns an object containing commonly used constants for file system
1645operations. The specific constants currently defined are described in
1646[FS constants][].
1647
1648## `fs.copyFile(src, dest[, flags], callback)`
1649<!-- YAML
1650added: v8.5.0
1651changes:
1652  - version: v14.0.0
1653    pr-url: https://github.com/nodejs/node/pull/27044
1654    description: Changed 'flags' argument to 'mode' and imposed
1655                 stricter type validation.
1656-->
1657
1658* `src` {string|Buffer|URL} source filename to copy
1659* `dest` {string|Buffer|URL} destination filename of the copy operation
1660* `flags` {number} modifiers for copy operation. **Default:** `0`.
1661* `callback` {Function}
1662
1663Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
1664already exists. No arguments other than a possible exception are given to the
1665callback function. Node.js makes no guarantees about the atomicity of the copy
1666operation. If an error occurs after the destination file has been opened for
1667writing, Node.js will attempt to remove the destination.
1668
1669`flags` is an optional integer that specifies the behavior
1670of the copy operation. It is possible to create a mask consisting of the bitwise
1671OR of two or more values (e.g.
1672`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
1673
1674* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
1675exists.
1676* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
1677copy-on-write reflink. If the platform does not support copy-on-write, then a
1678fallback copy mechanism is used.
1679* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
1680create a copy-on-write reflink. If the platform does not support copy-on-write,
1681then the operation will fail.
1682
1683```js
1684const fs = require('fs');
1685
1686// destination.txt will be created or overwritten by default.
1687fs.copyFile('source.txt', 'destination.txt', (err) => {
1688  if (err) throw err;
1689  console.log('source.txt was copied to destination.txt');
1690});
1691```
1692
1693If the third argument is a number, then it specifies `flags`:
1694
1695```js
1696const fs = require('fs');
1697const { COPYFILE_EXCL } = fs.constants;
1698
1699// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
1700fs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback);
1701```
1702
1703## `fs.copyFileSync(src, dest[, flags])`
1704<!-- YAML
1705added: v8.5.0
1706changes:
1707  - version: v14.0.0
1708    pr-url: https://github.com/nodejs/node/pull/27044
1709    description: Changed 'flags' argument to 'mode' and imposed
1710                 stricter type validation.
1711-->
1712
1713* `src` {string|Buffer|URL} source filename to copy
1714* `dest` {string|Buffer|URL} destination filename of the copy operation
1715* `flags` {number} modifiers for copy operation. **Default:** `0`.
1716
1717Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
1718already exists. Returns `undefined`. Node.js makes no guarantees about the
1719atomicity of the copy operation. If an error occurs after the destination file
1720has been opened for writing, Node.js will attempt to remove the destination.
1721
1722`flags` is an optional integer that specifies the behavior
1723of the copy operation. It is possible to create a mask consisting of the bitwise
1724OR of two or more values (e.g.
1725`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
1726
1727* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
1728exists.
1729* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
1730copy-on-write reflink. If the platform does not support copy-on-write, then a
1731fallback copy mechanism is used.
1732* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
1733create a copy-on-write reflink. If the platform does not support copy-on-write,
1734then the operation will fail.
1735
1736```js
1737const fs = require('fs');
1738
1739// destination.txt will be created or overwritten by default.
1740fs.copyFileSync('source.txt', 'destination.txt');
1741console.log('source.txt was copied to destination.txt');
1742```
1743
1744If the third argument is a number, then it specifies `flags`:
1745
1746```js
1747const fs = require('fs');
1748const { COPYFILE_EXCL } = fs.constants;
1749
1750// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
1751fs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL);
1752```
1753
1754## `fs.createReadStream(path[, options])`
1755<!-- YAML
1756added: v0.1.31
1757changes:
1758  - version: v12.10.0
1759    pr-url: https://github.com/nodejs/node/pull/29212
1760    description: Enable `emitClose` option.
1761  - version: v11.0.0
1762    pr-url: https://github.com/nodejs/node/pull/19898
1763    description: Impose new restrictions on `start` and `end`, throwing
1764                 more appropriate errors in cases when we cannot reasonably
1765                 handle the input values.
1766  - version: v7.6.0
1767    pr-url: https://github.com/nodejs/node/pull/10739
1768    description: The `path` parameter can be a WHATWG `URL` object using
1769                 `file:` protocol. Support is currently still *experimental*.
1770  - version: v7.0.0
1771    pr-url: https://github.com/nodejs/node/pull/7831
1772    description: The passed `options` object will never be modified.
1773  - version: v2.3.0
1774    pr-url: https://github.com/nodejs/node/pull/1845
1775    description: The passed `options` object can be a string now.
1776  - version: v12.17.0
1777    pr-url: https://github.com/nodejs/node/pull/29083
1778    description: The `fs` options allow overriding the used `fs`
1779                 implementation.
1780-->
1781
1782* `path` {string|Buffer|URL}
1783* `options` {string|Object}
1784  * `flags` {string} See [support of file system `flags`][]. **Default:**
1785  `'r'`.
1786  * `encoding` {string} **Default:** `null`
1787  * `fd` {integer} **Default:** `null`
1788  * `mode` {integer} **Default:** `0o666`
1789  * `autoClose` {boolean} **Default:** `true`
1790  * `emitClose` {boolean} **Default:** `false`
1791  * `start` {integer}
1792  * `end` {integer} **Default:** `Infinity`
1793  * `highWaterMark` {integer} **Default:** `64 * 1024`
1794  * `fs` {Object|null} **Default:** `null`
1795* Returns: {fs.ReadStream} See [Readable Stream][].
1796
1797Unlike the 16 kb default `highWaterMark` for a readable stream, the stream
1798returned by this method has a default `highWaterMark` of 64 kb.
1799
1800`options` can include `start` and `end` values to read a range of bytes from
1801the file instead of the entire file. Both `start` and `end` are inclusive and
1802start counting at 0, allowed values are in the
1803[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `fd` is specified and `start` is
1804omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
1805current file position. The `encoding` can be any one of those accepted by
1806[`Buffer`][].
1807
1808If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
1809the specified file descriptor. This means that no `'open'` event will be
1810emitted. `fd` should be blocking; non-blocking `fd`s should be passed to
1811[`net.Socket`][].
1812
1813If `fd` points to a character device that only supports blocking reads
1814(such as keyboard or sound card), read operations do not finish until data is
1815available. This can prevent the process from exiting and the stream from
1816closing naturally.
1817
1818By default, the stream will not emit a `'close'` event after it has been
1819destroyed. This is the opposite of the default for other `Readable` streams.
1820Set the `emitClose` option to `true` to change this behavior.
1821
1822By providing the `fs` option, it is possible to override the corresponding `fs`
1823implementations for `open`, `read`, and `close`. When providing the `fs` option,
1824overrides for `open`, `read`, and `close` are required.
1825
1826```js
1827const fs = require('fs');
1828// Create a stream from some character device.
1829const stream = fs.createReadStream('/dev/input/event0');
1830setTimeout(() => {
1831  stream.close(); // This may not close the stream.
1832  // Artificially marking end-of-stream, as if the underlying resource had
1833  // indicated end-of-file by itself, allows the stream to close.
1834  // This does not cancel pending read operations, and if there is such an
1835  // operation, the process may still not be able to exit successfully
1836  // until it finishes.
1837  stream.push(null);
1838  stream.read(0);
1839}, 100);
1840```
1841
1842If `autoClose` is false, then the file descriptor won't be closed, even if
1843there's an error. It is the application's responsibility to close it and make
1844sure there's no file descriptor leak. If `autoClose` is set to true (default
1845behavior), on `'error'` or `'end'` the file descriptor will be closed
1846automatically.
1847
1848`mode` sets the file mode (permission and sticky bits), but only if the
1849file was created.
1850
1851An example to read the last 10 bytes of a file which is 100 bytes long:
1852
1853```js
1854fs.createReadStream('sample.txt', { start: 90, end: 99 });
1855```
1856
1857If `options` is a string, then it specifies the encoding.
1858
1859## `fs.createWriteStream(path[, options])`
1860<!-- YAML
1861added: v0.1.31
1862changes:
1863  - version: v12.10.0
1864    pr-url: https://github.com/nodejs/node/pull/29212
1865    description: Enable `emitClose` option.
1866  - version: v7.6.0
1867    pr-url: https://github.com/nodejs/node/pull/10739
1868    description: The `path` parameter can be a WHATWG `URL` object using
1869                 `file:` protocol. Support is currently still *experimental*.
1870  - version: v7.0.0
1871    pr-url: https://github.com/nodejs/node/pull/7831
1872    description: The passed `options` object will never be modified.
1873  - version: v5.5.0
1874    pr-url: https://github.com/nodejs/node/pull/3679
1875    description: The `autoClose` option is supported now.
1876  - version: v2.3.0
1877    pr-url: https://github.com/nodejs/node/pull/1845
1878    description: The passed `options` object can be a string now.
1879  - version: v12.17.0
1880    pr-url: https://github.com/nodejs/node/pull/v12.17.0
1881    description: The `fs` options allow overriding the used `fs`
1882                 implementation.
1883-->
1884
1885* `path` {string|Buffer|URL}
1886* `options` {string|Object}
1887  * `flags` {string} See [support of file system `flags`][]. **Default:**
1888  `'w'`.
1889  * `encoding` {string} **Default:** `'utf8'`
1890  * `fd` {integer} **Default:** `null`
1891  * `mode` {integer} **Default:** `0o666`
1892  * `autoClose` {boolean} **Default:** `true`
1893  * `emitClose` {boolean} **Default:** `false`
1894  * `start` {integer}
1895  * `fs` {Object|null} **Default:** `null`
1896* Returns: {fs.WriteStream} See [Writable Stream][].
1897
1898`options` may also include a `start` option to allow writing data at
1899some position past the beginning of the file, allowed values are in the
1900[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather
1901than replacing it may require a `flags` mode of `r+` rather than the
1902default mode `w`. The `encoding` can be any one of those accepted by
1903[`Buffer`][].
1904
1905If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
1906the file descriptor will be closed automatically. If `autoClose` is false,
1907then the file descriptor won't be closed, even if there's an error.
1908It is the application's responsibility to close it and make sure there's no
1909file descriptor leak.
1910
1911By default, the stream will not emit a `'close'` event after it has been
1912destroyed. This is the opposite of the default for other `Writable` streams.
1913Set the `emitClose` option to `true` to change this behavior.
1914
1915By providing the `fs` option it is possible to override the corresponding `fs`
1916implementations for `open`, `write`, `writev` and `close`. Overriding `write()`
1917without `writev()` can reduce performance as some optimizations (`_writev()`)
1918will be disabled. When providing the `fs` option,  overrides for `open`,
1919`close`, and at least one of `write` and `writev` are required.
1920
1921Like [`ReadStream`][], if `fd` is specified, [`WriteStream`][] will ignore the
1922`path` argument and will use the specified file descriptor. This means that no
1923`'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s
1924should be passed to [`net.Socket`][].
1925
1926If `options` is a string, then it specifies the encoding.
1927
1928## `fs.exists(path, callback)`
1929<!-- YAML
1930added: v0.0.2
1931changes:
1932  - version: v7.6.0
1933    pr-url: https://github.com/nodejs/node/pull/10739
1934    description: The `path` parameter can be a WHATWG `URL` object using
1935                 `file:` protocol. Support is currently still *experimental*.
1936deprecated: v1.0.0
1937-->
1938
1939> Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
1940
1941* `path` {string|Buffer|URL}
1942* `callback` {Function}
1943  * `exists` {boolean}
1944
1945Test whether or not the given path exists by checking with the file system.
1946Then call the `callback` argument with either true or false:
1947
1948```js
1949fs.exists('/etc/passwd', (exists) => {
1950  console.log(exists ? 'it\'s there' : 'no passwd!');
1951});
1952```
1953
1954**The parameters for this callback are not consistent with other Node.js
1955callbacks.** Normally, the first parameter to a Node.js callback is an `err`
1956parameter, optionally followed by other parameters. The `fs.exists()` callback
1957has only one boolean parameter. This is one reason `fs.access()` is recommended
1958instead of `fs.exists()`.
1959
1960Using `fs.exists()` to check for the existence of a file before calling
1961`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing
1962so introduces a race condition, since other processes may change the file's
1963state between the two calls. Instead, user code should open/read/write the
1964file directly and handle the error raised if the file does not exist.
1965
1966**write (NOT RECOMMENDED)**
1967
1968```js
1969fs.exists('myfile', (exists) => {
1970  if (exists) {
1971    console.error('myfile already exists');
1972  } else {
1973    fs.open('myfile', 'wx', (err, fd) => {
1974      if (err) throw err;
1975      writeMyData(fd);
1976    });
1977  }
1978});
1979```
1980
1981**write (RECOMMENDED)**
1982
1983```js
1984fs.open('myfile', 'wx', (err, fd) => {
1985  if (err) {
1986    if (err.code === 'EEXIST') {
1987      console.error('myfile already exists');
1988      return;
1989    }
1990
1991    throw err;
1992  }
1993
1994  writeMyData(fd);
1995});
1996```
1997
1998**read (NOT RECOMMENDED)**
1999
2000```js
2001fs.exists('myfile', (exists) => {
2002  if (exists) {
2003    fs.open('myfile', 'r', (err, fd) => {
2004      if (err) throw err;
2005      readMyData(fd);
2006    });
2007  } else {
2008    console.error('myfile does not exist');
2009  }
2010});
2011```
2012
2013**read (RECOMMENDED)**
2014
2015```js
2016fs.open('myfile', 'r', (err, fd) => {
2017  if (err) {
2018    if (err.code === 'ENOENT') {
2019      console.error('myfile does not exist');
2020      return;
2021    }
2022
2023    throw err;
2024  }
2025
2026  readMyData(fd);
2027});
2028```
2029
2030The "not recommended" examples above check for existence and then use the
2031file; the "recommended" examples are better because they use the file directly
2032and handle the error, if any.
2033
2034In general, check for the existence of a file only if the file won’t be
2035used directly, for example when its existence is a signal from another
2036process.
2037
2038## `fs.existsSync(path)`
2039<!-- YAML
2040added: v0.1.21
2041changes:
2042  - version: v7.6.0
2043    pr-url: https://github.com/nodejs/node/pull/10739
2044    description: The `path` parameter can be a WHATWG `URL` object using
2045                 `file:` protocol. Support is currently still *experimental*.
2046-->
2047
2048* `path` {string|Buffer|URL}
2049* Returns: {boolean}
2050
2051Returns `true` if the path exists, `false` otherwise.
2052
2053For detailed information, see the documentation of the asynchronous version of
2054this API: [`fs.exists()`][].
2055
2056`fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`
2057parameter to `fs.exists()` accepts parameters that are inconsistent with other
2058Node.js callbacks. `fs.existsSync()` does not use a callback.
2059
2060```js
2061if (fs.existsSync('/etc/passwd')) {
2062  console.log('The path exists.');
2063}
2064```
2065
2066## `fs.fchmod(fd, mode, callback)`
2067<!-- YAML
2068added: v0.4.7
2069changes:
2070  - version: v10.0.0
2071    pr-url: https://github.com/nodejs/node/pull/12562
2072    description: The `callback` parameter is no longer optional. Not passing
2073                 it will throw a `TypeError` at runtime.
2074  - version: v7.0.0
2075    pr-url: https://github.com/nodejs/node/pull/7897
2076    description: The `callback` parameter is no longer optional. Not passing
2077                 it will emit a deprecation warning with id DEP0013.
2078-->
2079
2080* `fd` {integer}
2081* `mode` {string|integer}
2082* `callback` {Function}
2083  * `err` {Error}
2084
2085Asynchronous fchmod(2). No arguments other than a possible exception
2086are given to the completion callback.
2087
2088## `fs.fchmodSync(fd, mode)`
2089<!-- YAML
2090added: v0.4.7
2091-->
2092
2093* `fd` {integer}
2094* `mode` {string|integer}
2095
2096Synchronous fchmod(2). Returns `undefined`.
2097
2098## `fs.fchown(fd, uid, gid, callback)`
2099<!-- YAML
2100added: v0.4.7
2101changes:
2102  - version: v10.0.0
2103    pr-url: https://github.com/nodejs/node/pull/12562
2104    description: The `callback` parameter is no longer optional. Not passing
2105                 it will throw a `TypeError` at runtime.
2106  - version: v7.0.0
2107    pr-url: https://github.com/nodejs/node/pull/7897
2108    description: The `callback` parameter is no longer optional. Not passing
2109                 it will emit a deprecation warning with id DEP0013.
2110-->
2111
2112* `fd` {integer}
2113* `uid` {integer}
2114* `gid` {integer}
2115* `callback` {Function}
2116  * `err` {Error}
2117
2118Asynchronous fchown(2). No arguments other than a possible exception are given
2119to the completion callback.
2120
2121## `fs.fchownSync(fd, uid, gid)`
2122<!-- YAML
2123added: v0.4.7
2124-->
2125
2126* `fd` {integer}
2127* `uid` {integer}
2128* `gid` {integer}
2129
2130Synchronous fchown(2). Returns `undefined`.
2131
2132## `fs.fdatasync(fd, callback)`
2133<!-- YAML
2134added: v0.1.96
2135changes:
2136  - version: v10.0.0
2137    pr-url: https://github.com/nodejs/node/pull/12562
2138    description: The `callback` parameter is no longer optional. Not passing
2139                 it will throw a `TypeError` at runtime.
2140  - version: v7.0.0
2141    pr-url: https://github.com/nodejs/node/pull/7897
2142    description: The `callback` parameter is no longer optional. Not passing
2143                 it will emit a deprecation warning with id DEP0013.
2144-->
2145
2146* `fd` {integer}
2147* `callback` {Function}
2148  * `err` {Error}
2149
2150Asynchronous fdatasync(2). No arguments other than a possible exception are
2151given to the completion callback.
2152
2153## `fs.fdatasyncSync(fd)`
2154<!-- YAML
2155added: v0.1.96
2156-->
2157
2158* `fd` {integer}
2159
2160Synchronous fdatasync(2). Returns `undefined`.
2161
2162## `fs.fstat(fd[, options], callback)`
2163<!-- YAML
2164added: v0.1.95
2165changes:
2166  - version: v10.0.0
2167    pr-url: https://github.com/nodejs/node/pull/12562
2168    description: The `callback` parameter is no longer optional. Not passing
2169                 it will throw a `TypeError` at runtime.
2170  - version: v7.0.0
2171    pr-url: https://github.com/nodejs/node/pull/7897
2172    description: The `callback` parameter is no longer optional. Not passing
2173                 it will emit a deprecation warning with id DEP0013.
2174  - version: v10.5.0
2175    pr-url: https://github.com/nodejs/node/pull/20220
2176    description: Accepts an additional `options` object to specify whether
2177                 the numeric values returned should be bigint.
2178-->
2179
2180* `fd` {integer}
2181* `options` {Object}
2182  * `bigint` {boolean} Whether the numeric values in the returned
2183    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
2184* `callback` {Function}
2185  * `err` {Error}
2186  * `stats` {fs.Stats}
2187
2188Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
2189`stats` is an [`fs.Stats`][] object. `fstat()` is identical to [`stat()`][],
2190except that the file to be stat-ed is specified by the file descriptor `fd`.
2191
2192## `fs.fstatSync(fd[, options])`
2193<!-- YAML
2194added: v0.1.95
2195changes:
2196  - version: v10.5.0
2197    pr-url: https://github.com/nodejs/node/pull/20220
2198    description: Accepts an additional `options` object to specify whether
2199                 the numeric values returned should be bigint.
2200-->
2201
2202* `fd` {integer}
2203* `options` {Object}
2204  * `bigint` {boolean} Whether the numeric values in the returned
2205    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
2206* Returns: {fs.Stats}
2207
2208Synchronous fstat(2).
2209
2210## `fs.fsync(fd, callback)`
2211<!-- YAML
2212added: v0.1.96
2213changes:
2214  - version: v10.0.0
2215    pr-url: https://github.com/nodejs/node/pull/12562
2216    description: The `callback` parameter is no longer optional. Not passing
2217                 it will throw a `TypeError` at runtime.
2218  - version: v7.0.0
2219    pr-url: https://github.com/nodejs/node/pull/7897
2220    description: The `callback` parameter is no longer optional. Not passing
2221                 it will emit a deprecation warning with id DEP0013.
2222-->
2223
2224* `fd` {integer}
2225* `callback` {Function}
2226  * `err` {Error}
2227
2228Asynchronous fsync(2). No arguments other than a possible exception are given
2229to the completion callback.
2230
2231## `fs.fsyncSync(fd)`
2232<!-- YAML
2233added: v0.1.96
2234-->
2235
2236* `fd` {integer}
2237
2238Synchronous fsync(2). Returns `undefined`.
2239
2240## `fs.ftruncate(fd[, len], callback)`
2241<!-- YAML
2242added: v0.8.6
2243changes:
2244  - version: v10.0.0
2245    pr-url: https://github.com/nodejs/node/pull/12562
2246    description: The `callback` parameter is no longer optional. Not passing
2247                 it will throw a `TypeError` at runtime.
2248  - version: v7.0.0
2249    pr-url: https://github.com/nodejs/node/pull/7897
2250    description: The `callback` parameter is no longer optional. Not passing
2251                 it will emit a deprecation warning with id DEP0013.
2252-->
2253
2254* `fd` {integer}
2255* `len` {integer} **Default:** `0`
2256* `callback` {Function}
2257  * `err` {Error}
2258
2259Asynchronous ftruncate(2). No arguments other than a possible exception are
2260given to the completion callback.
2261
2262If the file referred to by the file descriptor was larger than `len` bytes, only
2263the first `len` bytes will be retained in the file.
2264
2265For example, the following program retains only the first four bytes of the
2266file:
2267
2268```js
2269console.log(fs.readFileSync('temp.txt', 'utf8'));
2270// Prints: Node.js
2271
2272// get the file descriptor of the file to be truncated
2273const fd = fs.openSync('temp.txt', 'r+');
2274
2275// Truncate the file to first four bytes
2276fs.ftruncate(fd, 4, (err) => {
2277  assert.ifError(err);
2278  console.log(fs.readFileSync('temp.txt', 'utf8'));
2279});
2280// Prints: Node
2281```
2282
2283If the file previously was shorter than `len` bytes, it is extended, and the
2284extended part is filled with null bytes (`'\0'`):
2285
2286```js
2287console.log(fs.readFileSync('temp.txt', 'utf8'));
2288// Prints: Node.js
2289
2290// get the file descriptor of the file to be truncated
2291const fd = fs.openSync('temp.txt', 'r+');
2292
2293// Truncate the file to 10 bytes, whereas the actual size is 7 bytes
2294fs.ftruncate(fd, 10, (err) => {
2295  assert.ifError(err);
2296  console.log(fs.readFileSync('temp.txt'));
2297});
2298// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>
2299// ('Node.js\0\0\0' in UTF8)
2300```
2301
2302The last three bytes are null bytes (`'\0'`), to compensate the over-truncation.
2303
2304## `fs.ftruncateSync(fd[, len])`
2305<!-- YAML
2306added: v0.8.6
2307-->
2308
2309* `fd` {integer}
2310* `len` {integer} **Default:** `0`
2311
2312Returns `undefined`.
2313
2314For detailed information, see the documentation of the asynchronous version of
2315this API: [`fs.ftruncate()`][].
2316
2317## `fs.futimes(fd, atime, mtime, callback)`
2318<!-- YAML
2319added: v0.4.2
2320changes:
2321  - version: v10.0.0
2322    pr-url: https://github.com/nodejs/node/pull/12562
2323    description: The `callback` parameter is no longer optional. Not passing
2324                 it will throw a `TypeError` at runtime.
2325  - version: v7.0.0
2326    pr-url: https://github.com/nodejs/node/pull/7897
2327    description: The `callback` parameter is no longer optional. Not passing
2328                 it will emit a deprecation warning with id DEP0013.
2329  - version: v4.1.0
2330    pr-url: https://github.com/nodejs/node/pull/2387
2331    description: Numeric strings, `NaN` and `Infinity` are now allowed
2332                 time specifiers.
2333-->
2334
2335* `fd` {integer}
2336* `atime` {number|string|Date}
2337* `mtime` {number|string|Date}
2338* `callback` {Function}
2339  * `err` {Error}
2340
2341Change the file system timestamps of the object referenced by the supplied file
2342descriptor. See [`fs.utimes()`][].
2343
2344This function does not work on AIX versions before 7.1, it will return the
2345error `UV_ENOSYS`.
2346
2347## `fs.futimesSync(fd, atime, mtime)`
2348<!-- YAML
2349added: v0.4.2
2350changes:
2351  - version: v4.1.0
2352    pr-url: https://github.com/nodejs/node/pull/2387
2353    description: Numeric strings, `NaN` and `Infinity` are now allowed
2354                 time specifiers.
2355-->
2356
2357* `fd` {integer}
2358* `atime` {number|string|Date}
2359* `mtime` {number|string|Date}
2360
2361Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
2362
2363## `fs.lchmod(path, mode, callback)`
2364<!-- YAML
2365deprecated: v0.4.7
2366changes:
2367  - version: v10.0.0
2368    pr-url: https://github.com/nodejs/node/pull/12562
2369    description: The `callback` parameter is no longer optional. Not passing
2370                 it will throw a `TypeError` at runtime.
2371  - version: v7.0.0
2372    pr-url: https://github.com/nodejs/node/pull/7897
2373    description: The `callback` parameter is no longer optional. Not passing
2374                 it will emit a deprecation warning with id DEP0013.
2375-->
2376
2377* `path` {string|Buffer|URL}
2378* `mode` {integer}
2379* `callback` {Function}
2380  * `err` {Error}
2381
2382Asynchronous lchmod(2). No arguments other than a possible exception
2383are given to the completion callback.
2384
2385Only available on macOS.
2386
2387## `fs.lchmodSync(path, mode)`
2388<!-- YAML
2389deprecated: v0.4.7
2390-->
2391
2392* `path` {string|Buffer|URL}
2393* `mode` {integer}
2394
2395Synchronous lchmod(2). Returns `undefined`.
2396
2397## `fs.lchown(path, uid, gid, callback)`
2398<!-- YAML
2399changes:
2400  - version: v10.6.0
2401    pr-url: https://github.com/nodejs/node/pull/21498
2402    description: This API is no longer deprecated.
2403  - version: v10.0.0
2404    pr-url: https://github.com/nodejs/node/pull/12562
2405    description: The `callback` parameter is no longer optional. Not passing
2406                 it will throw a `TypeError` at runtime.
2407  - version: v7.0.0
2408    pr-url: https://github.com/nodejs/node/pull/7897
2409    description: The `callback` parameter is no longer optional. Not passing
2410                 it will emit a deprecation warning with id DEP0013.
2411  - version: v0.4.7
2412    description: Documentation-only deprecation.
2413-->
2414
2415* `path` {string|Buffer|URL}
2416* `uid` {integer}
2417* `gid` {integer}
2418* `callback` {Function}
2419  * `err` {Error}
2420
2421Asynchronous lchown(2). No arguments other than a possible exception are given
2422to the completion callback.
2423
2424## `fs.lchownSync(path, uid, gid)`
2425<!-- YAML
2426changes:
2427  - version: v10.6.0
2428    pr-url: https://github.com/nodejs/node/pull/21498
2429    description: This API is no longer deprecated.
2430  - version: v0.4.7
2431    description: Documentation-only deprecation.
2432-->
2433
2434* `path` {string|Buffer|URL}
2435* `uid` {integer}
2436* `gid` {integer}
2437
2438Synchronous lchown(2). Returns `undefined`.
2439
2440## `fs.lutimes(path, atime, mtime, callback)`
2441<!-- YAML
2442added: v12.19.0
2443-->
2444
2445* `path` {string|Buffer|URL}
2446* `atime` {number|string|Date}
2447* `mtime` {number|string|Date}
2448* `callback` {Function}
2449  * `err` {Error}
2450
2451Changes the access and modification times of a file in the same way as
2452[`fs.utimes()`][], with the difference that if the path refers to a symbolic
2453link, then the link is not dereferenced: instead, the timestamps of the
2454symbolic link itself are changed.
2455
2456No arguments other than a possible exception are given to the completion
2457callback.
2458
2459## `fs.lutimesSync(path, atime, mtime)`
2460<!-- YAML
2461added: v12.19.0
2462-->
2463
2464* `path` {string|Buffer|URL}
2465* `atime` {number|string|Date}
2466* `mtime` {number|string|Date}
2467
2468Change the file system timestamps of the symbolic link referenced by `path`.
2469Returns `undefined`, or throws an exception when parameters are incorrect or
2470the operation fails. This is the synchronous version of [`fs.lutimes()`][].
2471
2472## `fs.link(existingPath, newPath, callback)`
2473<!-- YAML
2474added: v0.1.31
2475changes:
2476  - version: v10.0.0
2477    pr-url: https://github.com/nodejs/node/pull/12562
2478    description: The `callback` parameter is no longer optional. Not passing
2479                 it will throw a `TypeError` at runtime.
2480  - version: v7.6.0
2481    pr-url: https://github.com/nodejs/node/pull/10739
2482    description: The `existingPath` and `newPath` parameters can be WHATWG
2483                 `URL` objects using `file:` protocol. Support is currently
2484                 still *experimental*.
2485  - version: v7.0.0
2486    pr-url: https://github.com/nodejs/node/pull/7897
2487    description: The `callback` parameter is no longer optional. Not passing
2488                 it will emit a deprecation warning with id DEP0013.
2489-->
2490
2491* `existingPath` {string|Buffer|URL}
2492* `newPath` {string|Buffer|URL}
2493* `callback` {Function}
2494  * `err` {Error}
2495
2496Asynchronous link(2). No arguments other than a possible exception are given to
2497the completion callback.
2498
2499## `fs.linkSync(existingPath, newPath)`
2500<!-- YAML
2501added: v0.1.31
2502changes:
2503  - version: v7.6.0
2504    pr-url: https://github.com/nodejs/node/pull/10739
2505    description: The `existingPath` and `newPath` parameters can be WHATWG
2506                 `URL` objects using `file:` protocol. Support is currently
2507                 still *experimental*.
2508-->
2509
2510* `existingPath` {string|Buffer|URL}
2511* `newPath` {string|Buffer|URL}
2512
2513Synchronous link(2). Returns `undefined`.
2514
2515## `fs.lstat(path[, options], callback)`
2516<!-- YAML
2517added: v0.1.30
2518changes:
2519  - version: v10.0.0
2520    pr-url: https://github.com/nodejs/node/pull/12562
2521    description: The `callback` parameter is no longer optional. Not passing
2522                 it will throw a `TypeError` at runtime.
2523  - version: v7.6.0
2524    pr-url: https://github.com/nodejs/node/pull/10739
2525    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2526                 protocol. Support is currently still *experimental*.
2527  - version: v7.0.0
2528    pr-url: https://github.com/nodejs/node/pull/7897
2529    description: The `callback` parameter is no longer optional. Not passing
2530                 it will emit a deprecation warning with id DEP0013.
2531  - version: v10.5.0
2532    pr-url: https://github.com/nodejs/node/pull/20220
2533    description: Accepts an additional `options` object to specify whether
2534                 the numeric values returned should be bigint.
2535-->
2536
2537* `path` {string|Buffer|URL}
2538* `options` {Object}
2539  * `bigint` {boolean} Whether the numeric values in the returned
2540    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
2541* `callback` {Function}
2542  * `err` {Error}
2543  * `stats` {fs.Stats}
2544
2545Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
2546`stats` is a [`fs.Stats`][] object. `lstat()` is identical to `stat()`,
2547except that if `path` is a symbolic link, then the link itself is stat-ed,
2548not the file that it refers to.
2549
2550## `fs.lstatSync(path[, options])`
2551<!-- YAML
2552added: v0.1.30
2553changes:
2554  - version: v7.6.0
2555    pr-url: https://github.com/nodejs/node/pull/10739
2556    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2557                 protocol. Support is currently still *experimental*.
2558  - version: v10.5.0
2559    pr-url: https://github.com/nodejs/node/pull/20220
2560    description: Accepts an additional `options` object to specify whether
2561                 the numeric values returned should be bigint.
2562-->
2563
2564* `path` {string|Buffer|URL}
2565* `options` {Object}
2566  * `bigint` {boolean} Whether the numeric values in the returned
2567    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
2568* Returns: {fs.Stats}
2569
2570Synchronous lstat(2).
2571
2572## `fs.mkdir(path[, options], callback)`
2573<!-- YAML
2574added: v0.1.8
2575changes:
2576  - version: v12.17.0
2577    pr-url: https://github.com/nodejs/node/pull/31530
2578    description: In `recursive` mode, the callback now receives the first
2579                 created path as an argument.
2580  - version: v10.12.0
2581    pr-url: https://github.com/nodejs/node/pull/21875
2582    description: The second argument can now be an `options` object with
2583                 `recursive` and `mode` properties.
2584  - version: v10.0.0
2585    pr-url: https://github.com/nodejs/node/pull/12562
2586    description: The `callback` parameter is no longer optional. Not passing
2587                 it will throw a `TypeError` at runtime.
2588  - version: v7.6.0
2589    pr-url: https://github.com/nodejs/node/pull/10739
2590    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2591                 protocol. Support is currently still *experimental*.
2592  - version: v7.0.0
2593    pr-url: https://github.com/nodejs/node/pull/7897
2594    description: The `callback` parameter is no longer optional. Not passing
2595                 it will emit a deprecation warning with id DEP0013.
2596-->
2597
2598* `path` {string|Buffer|URL}
2599* `options` {Object|integer}
2600  * `recursive` {boolean} **Default:** `false`
2601  * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
2602* `callback` {Function}
2603  * `err` {Error}
2604
2605Asynchronously creates a directory.
2606
2607The callback is given a possible exception and, if `recursive` is `true`, the
2608first directory path created, `(err, [path])`.
2609
2610The optional `options` argument can be an integer specifying mode (permission
2611and sticky bits), or an object with a `mode` property and a `recursive`
2612property indicating whether parent directories should be created. Calling
2613`fs.mkdir()` when `path` is a directory that exists results in an error only
2614when `recursive` is false.
2615
2616```js
2617// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
2618fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
2619  if (err) throw err;
2620});
2621```
2622
2623On Windows, using `fs.mkdir()` on the root directory even with recursion will
2624result in an error:
2625
2626```js
2627fs.mkdir('/', { recursive: true }, (err) => {
2628  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
2629});
2630```
2631
2632See also: mkdir(2).
2633
2634## `fs.mkdirSync(path[, options])`
2635<!-- YAML
2636added: v0.1.21
2637changes:
2638  - version: v12.17.0
2639    pr-url: https://github.com/nodejs/node/pull/31530
2640    description: In `recursive` mode, the first created path is returned now.
2641  - version: v10.12.0
2642    pr-url: https://github.com/nodejs/node/pull/21875
2643    description: The second argument can now be an `options` object with
2644                 `recursive` and `mode` properties.
2645  - version: v7.6.0
2646    pr-url: https://github.com/nodejs/node/pull/10739
2647    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2648                 protocol. Support is currently still *experimental*.
2649-->
2650
2651* `path` {string|Buffer|URL}
2652* `options` {Object|integer}
2653  * `recursive` {boolean} **Default:** `false`
2654  * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
2655* Returns: {string|undefined}
2656
2657Synchronously creates a directory. Returns `undefined`, or if `recursive` is
2658`true`, the first directory path created.
2659This is the synchronous version of [`fs.mkdir()`][].
2660
2661See also: mkdir(2).
2662
2663## `fs.mkdtemp(prefix[, options], callback)`
2664<!-- YAML
2665added: v5.10.0
2666changes:
2667  - version: v10.0.0
2668    pr-url: https://github.com/nodejs/node/pull/12562
2669    description: The `callback` parameter is no longer optional. Not passing
2670                 it will throw a `TypeError` at runtime.
2671  - version: v7.0.0
2672    pr-url: https://github.com/nodejs/node/pull/7897
2673    description: The `callback` parameter is no longer optional. Not passing
2674                 it will emit a deprecation warning with id DEP0013.
2675  - version: v6.2.1
2676    pr-url: https://github.com/nodejs/node/pull/6828
2677    description: The `callback` parameter is optional now.
2678-->
2679
2680* `prefix` {string}
2681* `options` {string|Object}
2682  * `encoding` {string} **Default:** `'utf8'`
2683* `callback` {Function}
2684  * `err` {Error}
2685  * `directory` {string}
2686
2687Creates a unique temporary directory.
2688
2689Generates six random characters to be appended behind a required
2690`prefix` to create a unique temporary directory. Due to platform
2691inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
2692notably the BSDs, can return more than six random characters, and replace
2693trailing `X` characters in `prefix` with random characters.
2694
2695The created directory path is passed as a string to the callback's second
2696parameter.
2697
2698The optional `options` argument can be a string specifying an encoding, or an
2699object with an `encoding` property specifying the character encoding to use.
2700
2701```js
2702fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
2703  if (err) throw err;
2704  console.log(directory);
2705  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
2706});
2707```
2708
2709The `fs.mkdtemp()` method will append the six randomly selected characters
2710directly to the `prefix` string. For instance, given a directory `/tmp`, if the
2711intention is to create a temporary directory *within* `/tmp`, the `prefix`
2712must end with a trailing platform-specific path separator
2713(`require('path').sep`).
2714
2715```js
2716// The parent directory for the new temporary directory
2717const tmpDir = os.tmpdir();
2718
2719// This method is *INCORRECT*:
2720fs.mkdtemp(tmpDir, (err, directory) => {
2721  if (err) throw err;
2722  console.log(directory);
2723  // Will print something similar to `/tmpabc123`.
2724  // A new temporary directory is created at the file system root
2725  // rather than *within* the /tmp directory.
2726});
2727
2728// This method is *CORRECT*:
2729const { sep } = require('path');
2730fs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
2731  if (err) throw err;
2732  console.log(directory);
2733  // Will print something similar to `/tmp/abc123`.
2734  // A new temporary directory is created within
2735  // the /tmp directory.
2736});
2737```
2738
2739## `fs.mkdtempSync(prefix[, options])`
2740<!-- YAML
2741added: v5.10.0
2742-->
2743
2744* `prefix` {string}
2745* `options` {string|Object}
2746  * `encoding` {string} **Default:** `'utf8'`
2747* Returns: {string}
2748
2749Returns the created directory path.
2750
2751For detailed information, see the documentation of the asynchronous version of
2752this API: [`fs.mkdtemp()`][].
2753
2754The optional `options` argument can be a string specifying an encoding, or an
2755object with an `encoding` property specifying the character encoding to use.
2756
2757## `fs.open(path[, flags[, mode]], callback)`
2758<!-- YAML
2759added: v0.0.2
2760changes:
2761  - version: v11.1.0
2762    pr-url: https://github.com/nodejs/node/pull/23767
2763    description: The `flags` argument is now optional and defaults to `'r'`.
2764  - version: v9.9.0
2765    pr-url: https://github.com/nodejs/node/pull/18801
2766    description: The `as` and `as+` modes are supported now.
2767  - version: v7.6.0
2768    pr-url: https://github.com/nodejs/node/pull/10739
2769    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2770                 protocol. Support is currently still *experimental*.
2771-->
2772
2773* `path` {string|Buffer|URL}
2774* `flags` {string|number} See [support of file system `flags`][].
2775  **Default:** `'r'`.
2776* `mode` {string|integer} **Default:** `0o666` (readable and writable)
2777* `callback` {Function}
2778  * `err` {Error}
2779  * `fd` {integer}
2780
2781Asynchronous file open. See open(2).
2782
2783`mode` sets the file mode (permission and sticky bits), but only if the file was
2784created. On Windows, only the write permission can be manipulated; see
2785[`fs.chmod()`][].
2786
2787The callback gets two arguments `(err, fd)`.
2788
2789Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
2790by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains
2791a colon, Node.js will open a file system stream, as described by
2792[this MSDN page][MSDN-Using-Streams].
2793
2794Functions based on `fs.open()` exhibit this behavior as well:
2795`fs.writeFile()`, `fs.readFile()`, etc.
2796
2797## `fs.opendir(path[, options], callback)`
2798<!-- YAML
2799added: v12.12.0
2800changes:
2801  - version: v12.16.0
2802    pr-url: https://github.com/nodejs/node/pull/30114
2803    description: The `bufferSize` option was introduced.
2804-->
2805
2806* `path` {string|Buffer|URL}
2807* `options` {Object}
2808  * `encoding` {string|null} **Default:** `'utf8'`
2809  * `bufferSize` {number} Number of directory entries that are buffered
2810    internally when reading from the directory. Higher values lead to better
2811    performance but higher memory usage. **Default:** `32`
2812* `callback` {Function}
2813  * `err` {Error}
2814  * `dir` {fs.Dir}
2815
2816Asynchronously open a directory. See opendir(3).
2817
2818Creates an [`fs.Dir`][], which contains all further functions for reading from
2819and cleaning up the directory.
2820
2821The `encoding` option sets the encoding for the `path` while opening the
2822directory and subsequent read operations.
2823
2824## `fs.opendirSync(path[, options])`
2825<!-- YAML
2826added: v12.12.0
2827changes:
2828  - version: v12.16.0
2829    pr-url: https://github.com/nodejs/node/pull/30114
2830    description: The `bufferSize` option was introduced.
2831-->
2832
2833* `path` {string|Buffer|URL}
2834* `options` {Object}
2835  * `encoding` {string|null} **Default:** `'utf8'`
2836  * `bufferSize` {number} Number of directory entries that are buffered
2837    internally when reading from the directory. Higher values lead to better
2838    performance but higher memory usage. **Default:** `32`
2839* Returns: {fs.Dir}
2840
2841Synchronously open a directory. See opendir(3).
2842
2843Creates an [`fs.Dir`][], which contains all further functions for reading from
2844and cleaning up the directory.
2845
2846The `encoding` option sets the encoding for the `path` while opening the
2847directory and subsequent read operations.
2848
2849## `fs.openSync(path[, flags, mode])`
2850<!-- YAML
2851added: v0.1.21
2852changes:
2853  - version: v11.1.0
2854    pr-url: https://github.com/nodejs/node/pull/23767
2855    description: The `flags` argument is now optional and defaults to `'r'`.
2856  - version: v9.9.0
2857    pr-url: https://github.com/nodejs/node/pull/18801
2858    description: The `as` and `as+` modes are supported now.
2859  - version: v7.6.0
2860    pr-url: https://github.com/nodejs/node/pull/10739
2861    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2862                 protocol. Support is currently still *experimental*.
2863-->
2864
2865* `path` {string|Buffer|URL}
2866* `flags` {string|number} **Default:** `'r'`.
2867   See [support of file system `flags`][].
2868* `mode` {string|integer} **Default:** `0o666`
2869* Returns: {number}
2870
2871Returns an integer representing the file descriptor.
2872
2873For detailed information, see the documentation of the asynchronous version of
2874this API: [`fs.open()`][].
2875
2876## `fs.read(fd, buffer, offset, length, position, callback)`
2877<!-- YAML
2878added: v0.0.2
2879changes:
2880  - version: v10.10.0
2881    pr-url: https://github.com/nodejs/node/pull/22150
2882    description: The `buffer` parameter can now be any `TypedArray`, or a
2883                 `DataView`.
2884  - version: v7.4.0
2885    pr-url: https://github.com/nodejs/node/pull/10382
2886    description: The `buffer` parameter can now be a `Uint8Array`.
2887  - version: v6.0.0
2888    pr-url: https://github.com/nodejs/node/pull/4518
2889    description: The `length` parameter can now be `0`.
2890-->
2891
2892* `fd` {integer}
2893* `buffer` {Buffer|TypedArray|DataView}
2894* `offset` {integer}
2895* `length` {integer}
2896* `position` {integer}
2897* `callback` {Function}
2898  * `err` {Error}
2899  * `bytesRead` {integer}
2900  * `buffer` {Buffer}
2901
2902Read data from the file specified by `fd`.
2903
2904`buffer` is the buffer that the data (read from the fd) will be written to.
2905
2906`offset` is the offset in the buffer to start writing at.
2907
2908`length` is an integer specifying the number of bytes to read.
2909
2910`position` is an argument specifying where to begin reading from in the file.
2911If `position` is `null`, data will be read from the current file position,
2912and the file position will be updated.
2913If `position` is an integer, the file position will remain unchanged.
2914
2915The callback is given the three arguments, `(err, bytesRead, buffer)`.
2916
2917If this method is invoked as its [`util.promisify()`][]ed version, it returns
2918a `Promise` for an `Object` with `bytesRead` and `buffer` properties.
2919
2920## `fs.read(fd, [options,] callback)`
2921<!-- YAML
2922added: v12.17.0
2923changes:
2924  - version: v12.17.0
2925    pr-url: https://github.com/nodejs/node/pull/31402
2926    description: Options object can be passed in
2927                 to make Buffer, offset, length and position optional
2928-->
2929* `fd` {integer}
2930* `options` {Object}
2931  * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)`
2932  * `offset` {integer} **Default:** `0`
2933  * `length` {integer} **Default:** `buffer.length`
2934  * `position` {integer} **Default:** `null`
2935* `callback` {Function}
2936  * `err` {Error}
2937  * `bytesRead` {integer}
2938  * `buffer` {Buffer}
2939
2940Similar to the above `fs.read` function, this version takes an optional `options` object.
2941If no `options` object is specified, it will default with the above values.
2942
2943## `fs.readdir(path[, options], callback)`
2944<!-- YAML
2945added: v0.1.8
2946changes:
2947  - version: v10.10.0
2948    pr-url: https://github.com/nodejs/node/pull/22020
2949    description: New option `withFileTypes` was added.
2950  - version: v10.0.0
2951    pr-url: https://github.com/nodejs/node/pull/12562
2952    description: The `callback` parameter is no longer optional. Not passing
2953                 it will throw a `TypeError` at runtime.
2954  - version: v7.6.0
2955    pr-url: https://github.com/nodejs/node/pull/10739
2956    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2957                 protocol. Support is currently still *experimental*.
2958  - version: v7.0.0
2959    pr-url: https://github.com/nodejs/node/pull/7897
2960    description: The `callback` parameter is no longer optional. Not passing
2961                 it will emit a deprecation warning with id DEP0013.
2962  - version: v6.0.0
2963    pr-url: https://github.com/nodejs/node/pull/5616
2964    description: The `options` parameter was added.
2965-->
2966
2967* `path` {string|Buffer|URL}
2968* `options` {string|Object}
2969  * `encoding` {string} **Default:** `'utf8'`
2970  * `withFileTypes` {boolean} **Default:** `false`
2971* `callback` {Function}
2972  * `err` {Error}
2973  * `files` {string[]|Buffer[]|fs.Dirent[]}
2974
2975Asynchronous readdir(3). Reads the contents of a directory.
2976The callback gets two arguments `(err, files)` where `files` is an array of
2977the names of the files in the directory excluding `'.'` and `'..'`.
2978
2979The optional `options` argument can be a string specifying an encoding, or an
2980object with an `encoding` property specifying the character encoding to use for
2981the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
2982the filenames returned will be passed as `Buffer` objects.
2983
2984If `options.withFileTypes` is set to `true`, the `files` array will contain
2985[`fs.Dirent`][] objects.
2986
2987## `fs.readdirSync(path[, options])`
2988<!-- YAML
2989added: v0.1.21
2990changes:
2991  - version: v10.10.0
2992    pr-url: https://github.com/nodejs/node/pull/22020
2993    description: New option `withFileTypes` was added.
2994  - version: v7.6.0
2995    pr-url: https://github.com/nodejs/node/pull/10739
2996    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2997                 protocol. Support is currently still *experimental*.
2998-->
2999
3000* `path` {string|Buffer|URL}
3001* `options` {string|Object}
3002  * `encoding` {string} **Default:** `'utf8'`
3003  * `withFileTypes` {boolean} **Default:** `false`
3004* Returns: {string[]|Buffer[]|fs.Dirent[]}
3005
3006Synchronous readdir(3).
3007
3008The optional `options` argument can be a string specifying an encoding, or an
3009object with an `encoding` property specifying the character encoding to use for
3010the filenames returned. If the `encoding` is set to `'buffer'`,
3011the filenames returned will be passed as `Buffer` objects.
3012
3013If `options.withFileTypes` is set to `true`, the result will contain
3014[`fs.Dirent`][] objects.
3015
3016## `fs.readFile(path[, options], callback)`
3017<!-- YAML
3018added: v0.1.29
3019changes:
3020  - version: v10.0.0
3021    pr-url: https://github.com/nodejs/node/pull/12562
3022    description: The `callback` parameter is no longer optional. Not passing
3023                 it will throw a `TypeError` at runtime.
3024  - version: v7.6.0
3025    pr-url: https://github.com/nodejs/node/pull/10739
3026    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3027                 protocol. Support is currently still *experimental*.
3028  - version: v7.0.0
3029    pr-url: https://github.com/nodejs/node/pull/7897
3030    description: The `callback` parameter is no longer optional. Not passing
3031                 it will emit a deprecation warning with id DEP0013.
3032  - version: v5.1.0
3033    pr-url: https://github.com/nodejs/node/pull/3740
3034    description: The `callback` will always be called with `null` as the `error`
3035                 parameter in case of success.
3036  - version: v5.0.0
3037    pr-url: https://github.com/nodejs/node/pull/3163
3038    description: The `path` parameter can be a file descriptor now.
3039-->
3040
3041* `path` {string|Buffer|URL|integer} filename or file descriptor
3042* `options` {Object|string}
3043  * `encoding` {string|null} **Default:** `null`
3044  * `flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.
3045* `callback` {Function}
3046  * `err` {Error}
3047  * `data` {string|Buffer}
3048
3049Asynchronously reads the entire contents of a file.
3050
3051```js
3052fs.readFile('/etc/passwd', (err, data) => {
3053  if (err) throw err;
3054  console.log(data);
3055});
3056```
3057
3058The callback is passed two arguments `(err, data)`, where `data` is the
3059contents of the file.
3060
3061If no encoding is specified, then the raw buffer is returned.
3062
3063If `options` is a string, then it specifies the encoding:
3064
3065```js
3066fs.readFile('/etc/passwd', 'utf8', callback);
3067```
3068
3069When the path is a directory, the behavior of `fs.readFile()` and
3070[`fs.readFileSync()`][] is platform-specific. On macOS, Linux, and Windows, an
3071error will be returned. On FreeBSD, a representation of the directory's contents
3072will be returned.
3073
3074```js
3075// macOS, Linux, and Windows
3076fs.readFile('<directory>', (err, data) => {
3077  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
3078});
3079
3080//  FreeBSD
3081fs.readFile('<directory>', (err, data) => {
3082  // => null, <data>
3083});
3084```
3085
3086The `fs.readFile()` function buffers the entire file. To minimize memory costs,
3087when possible prefer streaming via `fs.createReadStream()`.
3088
3089### File descriptors
3090
30911. Any specified file descriptor has to support reading.
30922. If a file descriptor is specified as the `path`, it will not be closed
3093automatically.
30943. The reading will begin at the current position. For example, if the file
3095already had `'Hello World`' and six bytes are read with the file descriptor,
3096the call to `fs.readFile()` with the same file descriptor, would give
3097`'World'`, rather than `'Hello World'`.
3098
3099## `fs.readFileSync(path[, options])`
3100<!-- YAML
3101added: v0.1.8
3102changes:
3103  - version: v7.6.0
3104    pr-url: https://github.com/nodejs/node/pull/10739
3105    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3106                 protocol. Support is currently still *experimental*.
3107  - version: v5.0.0
3108    pr-url: https://github.com/nodejs/node/pull/3163
3109    description: The `path` parameter can be a file descriptor now.
3110-->
3111
3112* `path` {string|Buffer|URL|integer} filename or file descriptor
3113* `options` {Object|string}
3114  * `encoding` {string|null} **Default:** `null`
3115  * `flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.
3116* Returns: {string|Buffer}
3117
3118Returns the contents of the `path`.
3119
3120For detailed information, see the documentation of the asynchronous version of
3121this API: [`fs.readFile()`][].
3122
3123If the `encoding` option is specified then this function returns a
3124string. Otherwise it returns a buffer.
3125
3126Similar to [`fs.readFile()`][], when the path is a directory, the behavior of
3127`fs.readFileSync()` is platform-specific.
3128
3129```js
3130// macOS, Linux, and Windows
3131fs.readFileSync('<directory>');
3132// => [Error: EISDIR: illegal operation on a directory, read <directory>]
3133
3134//  FreeBSD
3135fs.readFileSync('<directory>'); // => <data>
3136```
3137
3138## `fs.readlink(path[, options], callback)`
3139<!-- YAML
3140added: v0.1.31
3141changes:
3142  - version: v10.0.0
3143    pr-url: https://github.com/nodejs/node/pull/12562
3144    description: The `callback` parameter is no longer optional. Not passing
3145                 it will throw a `TypeError` at runtime.
3146  - version: v7.6.0
3147    pr-url: https://github.com/nodejs/node/pull/10739
3148    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3149                 protocol. Support is currently still *experimental*.
3150  - version: v7.0.0
3151    pr-url: https://github.com/nodejs/node/pull/7897
3152    description: The `callback` parameter is no longer optional. Not passing
3153                 it will emit a deprecation warning with id DEP0013.
3154-->
3155
3156* `path` {string|Buffer|URL}
3157* `options` {string|Object}
3158  * `encoding` {string} **Default:** `'utf8'`
3159* `callback` {Function}
3160  * `err` {Error}
3161  * `linkString` {string|Buffer}
3162
3163Asynchronous readlink(2). The callback gets two arguments `(err,
3164linkString)`.
3165
3166The optional `options` argument can be a string specifying an encoding, or an
3167object with an `encoding` property specifying the character encoding to use for
3168the link path passed to the callback. If the `encoding` is set to `'buffer'`,
3169the link path returned will be passed as a `Buffer` object.
3170
3171## `fs.readlinkSync(path[, options])`
3172<!-- YAML
3173added: v0.1.31
3174changes:
3175  - version: v7.6.0
3176    pr-url: https://github.com/nodejs/node/pull/10739
3177    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3178                 protocol. Support is currently still *experimental*.
3179-->
3180
3181* `path` {string|Buffer|URL}
3182* `options` {string|Object}
3183  * `encoding` {string} **Default:** `'utf8'`
3184* Returns: {string|Buffer}
3185
3186Synchronous readlink(2). Returns the symbolic link's string value.
3187
3188The optional `options` argument can be a string specifying an encoding, or an
3189object with an `encoding` property specifying the character encoding to use for
3190the link path returned. If the `encoding` is set to `'buffer'`,
3191the link path returned will be passed as a `Buffer` object.
3192
3193## `fs.readSync(fd, buffer, offset, length, position)`
3194<!-- YAML
3195added: v0.1.21
3196changes:
3197  - version: v10.10.0
3198    pr-url: https://github.com/nodejs/node/pull/22150
3199    description: The `buffer` parameter can now be any `TypedArray` or a
3200                 `DataView`.
3201  - version: v6.0.0
3202    pr-url: https://github.com/nodejs/node/pull/4518
3203    description: The `length` parameter can now be `0`.
3204-->
3205
3206* `fd` {integer}
3207* `buffer` {Buffer|TypedArray|DataView}
3208* `offset` {integer}
3209* `length` {integer}
3210* `position` {integer}
3211* Returns: {number}
3212
3213Returns the number of `bytesRead`.
3214
3215For detailed information, see the documentation of the asynchronous version of
3216this API: [`fs.read()`][].
3217
3218## `fs.readSync(fd, buffer, [options])`
3219<!-- YAML
3220added: v12.17.0
3221changes:
3222  - version: v12.17.0
3223    pr-url: https://github.com/nodejs/node/pull/32460
3224    description: Options object can be passed in
3225                 to make offset, length and position optional
3226-->
3227
3228* `fd` {integer}
3229* `buffer` {Buffer|TypedArray|DataView}
3230* `options` {Object}
3231  * `offset` {integer} **Default:** `0`
3232  * `length` {integer} **Default:** `buffer.length`
3233  * `position` {integer} **Default:** `null`
3234* Returns: {number}
3235
3236Returns the number of `bytesRead`.
3237
3238Similar to the above `fs.readSync` function, this version takes an optional `options` object.
3239If no `options` object is specified, it will default with the above values.
3240
3241For detailed information, see the documentation of the asynchronous version of
3242this API: [`fs.read()`][].
3243
3244## `fs.readv(fd, buffers[, position], callback)`
3245<!-- YAML
3246added: v12.17.0
3247-->
3248
3249* `fd` {integer}
3250* `buffers` {ArrayBufferView[]}
3251* `position` {integer}
3252* `callback` {Function}
3253  * `err` {Error}
3254  * `bytesRead` {integer}
3255  * `buffers` {ArrayBufferView[]}
3256
3257Read from a file specified by `fd` and write to an array of `ArrayBufferView`s
3258using `readv()`.
3259
3260`position` is the offset from the beginning of the file from where data
3261should be read. If `typeof position !== 'number'`, the data will be read
3262from the current position.
3263
3264The callback will be given three arguments: `err`, `bytesRead`, and
3265`buffers`. `bytesRead` is how many bytes were read from the file.
3266
3267If this method is invoked as its [`util.promisify()`][]ed version, it returns
3268a `Promise` for an `Object` with `bytesRead` and `buffers` properties.
3269
3270## `fs.readvSync(fd, buffers[, position])`
3271<!-- YAML
3272added: v12.17.0
3273-->
3274
3275* `fd` {integer}
3276* `buffers` {ArrayBufferView[]}
3277* `position` {integer}
3278* Returns: {number} The number of bytes read.
3279
3280For detailed information, see the documentation of the asynchronous version of
3281this API: [`fs.readv()`][].
3282
3283## `fs.realpath(path[, options], callback)`
3284<!-- YAML
3285added: v0.1.31
3286changes:
3287  - version: v10.0.0
3288    pr-url: https://github.com/nodejs/node/pull/12562
3289    description: The `callback` parameter is no longer optional. Not passing
3290                 it will throw a `TypeError` at runtime.
3291  - version: v8.0.0
3292    pr-url: https://github.com/nodejs/node/pull/13028
3293    description: Pipe/Socket resolve support was added.
3294  - version: v7.6.0
3295    pr-url: https://github.com/nodejs/node/pull/10739
3296    description: The `path` parameter can be a WHATWG `URL` object using
3297                 `file:` protocol. Support is currently still *experimental*.
3298  - version: v7.0.0
3299    pr-url: https://github.com/nodejs/node/pull/7897
3300    description: The `callback` parameter is no longer optional. Not passing
3301                 it will emit a deprecation warning with id DEP0013.
3302  - version: v6.4.0
3303    pr-url: https://github.com/nodejs/node/pull/7899
3304    description: Calling `realpath` now works again for various edge cases
3305                 on Windows.
3306  - version: v6.0.0
3307    pr-url: https://github.com/nodejs/node/pull/3594
3308    description: The `cache` parameter was removed.
3309-->
3310
3311* `path` {string|Buffer|URL}
3312* `options` {string|Object}
3313  * `encoding` {string} **Default:** `'utf8'`
3314* `callback` {Function}
3315  * `err` {Error}
3316  * `resolvedPath` {string|Buffer}
3317
3318Asynchronously computes the canonical pathname by resolving `.`, `..` and
3319symbolic links.
3320
3321A canonical pathname is not necessarily unique. Hard links and bind mounts can
3322expose a file system entity through many pathnames.
3323
3324This function behaves like realpath(3), with some exceptions:
3325
33261. No case conversion is performed on case-insensitive file systems.
3327
33282. The maximum number of symbolic links is platform-independent and generally
3329   (much) higher than what the native realpath(3) implementation supports.
3330
3331The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`
3332to resolve relative paths.
3333
3334Only paths that can be converted to UTF8 strings are supported.
3335
3336The optional `options` argument can be a string specifying an encoding, or an
3337object with an `encoding` property specifying the character encoding to use for
3338the path passed to the callback. If the `encoding` is set to `'buffer'`,
3339the path returned will be passed as a `Buffer` object.
3340
3341If `path` resolves to a socket or a pipe, the function will return a system
3342dependent name for that object.
3343
3344## `fs.realpath.native(path[, options], callback)`
3345<!-- YAML
3346added: v9.2.0
3347-->
3348
3349* `path` {string|Buffer|URL}
3350* `options` {string|Object}
3351  * `encoding` {string} **Default:** `'utf8'`
3352* `callback` {Function}
3353  * `err` {Error}
3354  * `resolvedPath` {string|Buffer}
3355
3356Asynchronous realpath(3).
3357
3358The `callback` gets two arguments `(err, resolvedPath)`.
3359
3360Only paths that can be converted to UTF8 strings are supported.
3361
3362The optional `options` argument can be a string specifying an encoding, or an
3363object with an `encoding` property specifying the character encoding to use for
3364the path passed to the callback. If the `encoding` is set to `'buffer'`,
3365the path returned will be passed as a `Buffer` object.
3366
3367On Linux, when Node.js is linked against musl libc, the procfs file system must
3368be mounted on `/proc` in order for this function to work. Glibc does not have
3369this restriction.
3370
3371## `fs.realpathSync(path[, options])`
3372<!-- YAML
3373added: v0.1.31
3374changes:
3375  - version: v8.0.0
3376    pr-url: https://github.com/nodejs/node/pull/13028
3377    description: Pipe/Socket resolve support was added.
3378  - version: v7.6.0
3379    pr-url: https://github.com/nodejs/node/pull/10739
3380    description: The `path` parameter can be a WHATWG `URL` object using
3381                 `file:` protocol. Support is currently still *experimental*.
3382  - version: v6.4.0
3383    pr-url: https://github.com/nodejs/node/pull/7899
3384    description: Calling `realpathSync` now works again for various edge cases
3385                 on Windows.
3386  - version: v6.0.0
3387    pr-url: https://github.com/nodejs/node/pull/3594
3388    description: The `cache` parameter was removed.
3389-->
3390
3391* `path` {string|Buffer|URL}
3392* `options` {string|Object}
3393  * `encoding` {string} **Default:** `'utf8'`
3394* Returns: {string|Buffer}
3395
3396Returns the resolved pathname.
3397
3398For detailed information, see the documentation of the asynchronous version of
3399this API: [`fs.realpath()`][].
3400
3401## `fs.realpathSync.native(path[, options])`
3402<!-- YAML
3403added: v9.2.0
3404-->
3405
3406* `path` {string|Buffer|URL}
3407* `options` {string|Object}
3408  * `encoding` {string} **Default:** `'utf8'`
3409* Returns: {string|Buffer}
3410
3411Synchronous realpath(3).
3412
3413Only paths that can be converted to UTF8 strings are supported.
3414
3415The optional `options` argument can be a string specifying an encoding, or an
3416object with an `encoding` property specifying the character encoding to use for
3417the path returned. If the `encoding` is set to `'buffer'`,
3418the path returned will be passed as a `Buffer` object.
3419
3420On Linux, when Node.js is linked against musl libc, the procfs file system must
3421be mounted on `/proc` in order for this function to work. Glibc does not have
3422this restriction.
3423
3424## `fs.rename(oldPath, newPath, callback)`
3425<!-- YAML
3426added: v0.0.2
3427changes:
3428  - version: v10.0.0
3429    pr-url: https://github.com/nodejs/node/pull/12562
3430    description: The `callback` parameter is no longer optional. Not passing
3431                 it will throw a `TypeError` at runtime.
3432  - version: v7.6.0
3433    pr-url: https://github.com/nodejs/node/pull/10739
3434    description: The `oldPath` and `newPath` parameters can be WHATWG `URL`
3435                 objects using `file:` protocol. Support is currently still
3436                 *experimental*.
3437  - version: v7.0.0
3438    pr-url: https://github.com/nodejs/node/pull/7897
3439    description: The `callback` parameter is no longer optional. Not passing
3440                 it will emit a deprecation warning with id DEP0013.
3441-->
3442
3443* `oldPath` {string|Buffer|URL}
3444* `newPath` {string|Buffer|URL}
3445* `callback` {Function}
3446  * `err` {Error}
3447
3448Asynchronously rename file at `oldPath` to the pathname provided
3449as `newPath`. In the case that `newPath` already exists, it will
3450be overwritten. If there is a directory at `newPath`, an error will
3451be raised instead. No arguments other than a possible exception are
3452given to the completion callback.
3453
3454See also: rename(2).
3455
3456```js
3457fs.rename('oldFile.txt', 'newFile.txt', (err) => {
3458  if (err) throw err;
3459  console.log('Rename complete!');
3460});
3461```
3462
3463## `fs.renameSync(oldPath, newPath)`
3464<!-- YAML
3465added: v0.1.21
3466changes:
3467  - version: v7.6.0
3468    pr-url: https://github.com/nodejs/node/pull/10739
3469    description: The `oldPath` and `newPath` parameters can be WHATWG `URL`
3470                 objects using `file:` protocol. Support is currently still
3471                 *experimental*.
3472-->
3473
3474* `oldPath` {string|Buffer|URL}
3475* `newPath` {string|Buffer|URL}
3476
3477Synchronous rename(2). Returns `undefined`.
3478
3479## `fs.rmdir(path[, options], callback)`
3480<!-- YAML
3481added: v0.0.2
3482changes:
3483  - version: v12.16.0
3484    pr-url: https://github.com/nodejs/node/pull/30644
3485    description: The `maxBusyTries` option is renamed to `maxRetries`, and its
3486                 default is 0. The `emfileWait` option has been removed, and
3487                 `EMFILE` errors use the same retry logic as other errors. The
3488                 `retryDelay` option is now supported. `ENFILE` errors are now
3489                 retried.
3490  - version: v12.10.0
3491    pr-url: https://github.com/nodejs/node/pull/29168
3492    description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
3493                 now supported.
3494  - version: v10.0.0
3495    pr-url: https://github.com/nodejs/node/pull/12562
3496    description: The `callback` parameter is no longer optional. Not passing
3497                 it will throw a `TypeError` at runtime.
3498  - version: v7.6.0
3499    pr-url: https://github.com/nodejs/node/pull/10739
3500    description: The `path` parameters can be a WHATWG `URL` object using
3501                 `file:` protocol. Support is currently still *experimental*.
3502  - version: v7.0.0
3503    pr-url: https://github.com/nodejs/node/pull/7897
3504    description: The `callback` parameter is no longer optional. Not passing
3505                 it will emit a deprecation warning with id DEP0013.
3506-->
3507
3508> Stability: 1 - Recursive removal is experimental.
3509
3510* `path` {string|Buffer|URL}
3511* `options` {Object}
3512  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
3513  `EPERM` error is encountered, Node.js will retry the operation with a linear
3514  backoff wait of `retryDelay` ms longer on each try. This option represents the
3515  number of retries. This option is ignored if the `recursive` option is not
3516  `true`. **Default:** `0`.
3517  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
3518  recursive mode, errors are not reported if `path` does not exist, and
3519  operations are retried on failure. **Default:** `false`.
3520  * `retryDelay` {integer} The amount of time in milliseconds to wait between
3521  retries. This option is ignored if the `recursive` option is not `true`.
3522  **Default:** `100`.
3523* `callback` {Function}
3524  * `err` {Error}
3525
3526Asynchronous rmdir(2). No arguments other than a possible exception are given
3527to the completion callback.
3528
3529Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on
3530Windows and an `ENOTDIR` error on POSIX.
3531
3532## `fs.rmdirSync(path[, options])`
3533<!-- YAML
3534added: v0.1.21
3535changes:
3536  - version: v12.16.0
3537    pr-url: https://github.com/nodejs/node/pull/30644
3538    description: The `maxBusyTries` option is renamed to `maxRetries`, and its
3539                 default is 0. The `emfileWait` option has been removed, and
3540                 `EMFILE` errors use the same retry logic as other errors. The
3541                 `retryDelay` option is now supported. `ENFILE` errors are now
3542                 retried.
3543  - version: v12.10.0
3544    pr-url: https://github.com/nodejs/node/pull/29168
3545    description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
3546                 now supported.
3547  - version: v7.6.0
3548    pr-url: https://github.com/nodejs/node/pull/10739
3549    description: The `path` parameters can be a WHATWG `URL` object using
3550                 `file:` protocol. Support is currently still *experimental*.
3551-->
3552
3553> Stability: 1 - Recursive removal is experimental.
3554
3555* `path` {string|Buffer|URL}
3556* `options` {Object}
3557  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
3558  `EPERM` error is encountered, Node.js will retry the operation with a linear
3559  backoff wait of `retryDelay` ms longer on each try. This option represents the
3560  number of retries. This option is ignored if the `recursive` option is not
3561  `true`. **Default:** `0`.
3562  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
3563  recursive mode, errors are not reported if `path` does not exist, and
3564  operations are retried on failure. **Default:** `false`.
3565  * `retryDelay` {integer} The amount of time in milliseconds to wait between
3566  retries. This option is ignored if the `recursive` option is not `true`.
3567  **Default:** `100`.
3568
3569Synchronous rmdir(2). Returns `undefined`.
3570
3571Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
3572on Windows and an `ENOTDIR` error on POSIX.
3573
3574## `fs.stat(path[, options], callback)`
3575<!-- YAML
3576added: v0.0.2
3577changes:
3578  - version: v10.0.0
3579    pr-url: https://github.com/nodejs/node/pull/12562
3580    description: The `callback` parameter is no longer optional. Not passing
3581                 it will throw a `TypeError` at runtime.
3582  - version: v7.6.0
3583    pr-url: https://github.com/nodejs/node/pull/10739
3584    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3585                 protocol. Support is currently still *experimental*.
3586  - version: v7.0.0
3587    pr-url: https://github.com/nodejs/node/pull/7897
3588    description: The `callback` parameter is no longer optional. Not passing
3589                 it will emit a deprecation warning with id DEP0013.
3590  - version: v10.5.0
3591    pr-url: https://github.com/nodejs/node/pull/20220
3592    description: Accepts an additional `options` object to specify whether
3593                 the numeric values returned should be bigint.
3594-->
3595
3596* `path` {string|Buffer|URL}
3597* `options` {Object}
3598  * `bigint` {boolean} Whether the numeric values in the returned
3599    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
3600* `callback` {Function}
3601  * `err` {Error}
3602  * `stats` {fs.Stats}
3603
3604Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
3605`stats` is an [`fs.Stats`][] object.
3606
3607In case of an error, the `err.code` will be one of [Common System Errors][].
3608
3609Using `fs.stat()` to check for the existence of a file before calling
3610`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended.
3611Instead, user code should open/read/write the file directly and handle the
3612error raised if the file is not available.
3613
3614To check if a file exists without manipulating it afterwards, [`fs.access()`][]
3615is recommended.
3616
3617For example, given the following directory structure:
3618
3619```text
3620- txtDir
3621-- file.txt
3622- app.js
3623```
3624
3625The next program will check for the stats of the given paths:
3626
3627```js
3628const fs = require('fs');
3629
3630const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
3631
3632for (let i = 0; i < pathsToCheck.length; i++) {
3633  fs.stat(pathsToCheck[i], function(err, stats) {
3634    console.log(stats.isDirectory());
3635    console.log(stats);
3636  });
3637}
3638```
3639
3640The resulting output will resemble:
3641
3642```console
3643true
3644Stats {
3645  dev: 16777220,
3646  mode: 16877,
3647  nlink: 3,
3648  uid: 501,
3649  gid: 20,
3650  rdev: 0,
3651  blksize: 4096,
3652  ino: 14214262,
3653  size: 96,
3654  blocks: 0,
3655  atimeMs: 1561174653071.963,
3656  mtimeMs: 1561174614583.3518,
3657  ctimeMs: 1561174626623.5366,
3658  birthtimeMs: 1561174126937.2893,
3659  atime: 2019-06-22T03:37:33.072Z,
3660  mtime: 2019-06-22T03:36:54.583Z,
3661  ctime: 2019-06-22T03:37:06.624Z,
3662  birthtime: 2019-06-22T03:28:46.937Z
3663}
3664false
3665Stats {
3666  dev: 16777220,
3667  mode: 33188,
3668  nlink: 1,
3669  uid: 501,
3670  gid: 20,
3671  rdev: 0,
3672  blksize: 4096,
3673  ino: 14214074,
3674  size: 8,
3675  blocks: 8,
3676  atimeMs: 1561174616618.8555,
3677  mtimeMs: 1561174614584,
3678  ctimeMs: 1561174614583.8145,
3679  birthtimeMs: 1561174007710.7478,
3680  atime: 2019-06-22T03:36:56.619Z,
3681  mtime: 2019-06-22T03:36:54.584Z,
3682  ctime: 2019-06-22T03:36:54.584Z,
3683  birthtime: 2019-06-22T03:26:47.711Z
3684}
3685```
3686
3687## `fs.statSync(path[, options])`
3688<!-- YAML
3689added: v0.1.21
3690changes:
3691  - version: v7.6.0
3692    pr-url: https://github.com/nodejs/node/pull/10739
3693    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3694                 protocol. Support is currently still *experimental*.
3695  - version: v10.5.0
3696    pr-url: https://github.com/nodejs/node/pull/20220
3697    description: Accepts an additional `options` object to specify whether
3698                 the numeric values returned should be bigint.
3699-->
3700
3701* `path` {string|Buffer|URL}
3702* `options` {Object}
3703  * `bigint` {boolean} Whether the numeric values in the returned
3704    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
3705* Returns: {fs.Stats}
3706
3707Synchronous stat(2).
3708
3709## `fs.symlink(target, path[, type], callback)`
3710<!-- YAML
3711added: v0.1.31
3712changes:
3713  - version: v7.6.0
3714    pr-url: https://github.com/nodejs/node/pull/10739
3715    description: The `target` and `path` parameters can be WHATWG `URL` objects
3716                 using `file:` protocol. Support is currently still
3717                 *experimental*.
3718  - version: v12.0.0
3719    pr-url: https://github.com/nodejs/node/pull/23724
3720    description: If the `type` argument is left undefined, Node will autodetect
3721                 `target` type and automatically select `dir` or `file`
3722-->
3723
3724* `target` {string|Buffer|URL}
3725* `path` {string|Buffer|URL}
3726* `type` {string}
3727* `callback` {Function}
3728  * `err` {Error}
3729
3730Asynchronous symlink(2) which creates the link called `path` pointing to
3731`target`. No arguments other than a possible exception are given to the
3732completion callback.
3733
3734The `type` argument is only available on Windows and ignored on other platforms.
3735It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is
3736not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If
3737the `target` does not exist, `'file'` will be used. Windows junction points
3738require the destination path to be absolute. When using `'junction'`, the
3739`target` argument will automatically be normalized to absolute path.
3740
3741Relative targets are relative to the link’s parent directory.
3742
3743```js
3744fs.symlink('./mew', './example/mewtwo', callback);
3745```
3746
3747The above example creates a symbolic link `mewtwo` in the `example` which points
3748to `mew` in the same directory:
3749
3750```bash
3751$ tree example/
3752example/
3753├── mew
3754└── mewtwo -> ./mew
3755```
3756
3757## `fs.symlinkSync(target, path[, type])`
3758<!-- YAML
3759added: v0.1.31
3760changes:
3761  - version: v7.6.0
3762    pr-url: https://github.com/nodejs/node/pull/10739
3763    description: The `target` and `path` parameters can be WHATWG `URL` objects
3764                 using `file:` protocol. Support is currently still
3765                 *experimental*.
3766  - version: v12.0.0
3767    pr-url: https://github.com/nodejs/node/pull/23724
3768    description: If the `type` argument is left undefined, Node will autodetect
3769                 `target` type and automatically select `dir` or `file`
3770-->
3771
3772* `target` {string|Buffer|URL}
3773* `path` {string|Buffer|URL}
3774* `type` {string}
3775
3776Returns `undefined`.
3777
3778For detailed information, see the documentation of the asynchronous version of
3779this API: [`fs.symlink()`][].
3780
3781## `fs.truncate(path[, len], callback)`
3782<!-- YAML
3783added: v0.8.6
3784changes:
3785  - version: v10.0.0
3786    pr-url: https://github.com/nodejs/node/pull/12562
3787    description: The `callback` parameter is no longer optional. Not passing
3788                 it will throw a `TypeError` at runtime.
3789  - version: v7.0.0
3790    pr-url: https://github.com/nodejs/node/pull/7897
3791    description: The `callback` parameter is no longer optional. Not passing
3792                 it will emit a deprecation warning with id DEP0013.
3793-->
3794
3795* `path` {string|Buffer|URL}
3796* `len` {integer} **Default:** `0`
3797* `callback` {Function}
3798  * `err` {Error}
3799
3800Asynchronous truncate(2). No arguments other than a possible exception are
3801given to the completion callback. A file descriptor can also be passed as the
3802first argument. In this case, `fs.ftruncate()` is called.
3803
3804Passing a file descriptor is deprecated and may result in an error being thrown
3805in the future.
3806
3807## `fs.truncateSync(path[, len])`
3808<!-- YAML
3809added: v0.8.6
3810-->
3811
3812* `path` {string|Buffer|URL}
3813* `len` {integer} **Default:** `0`
3814
3815Synchronous truncate(2). Returns `undefined`. A file descriptor can also be
3816passed as the first argument. In this case, `fs.ftruncateSync()` is called.
3817
3818Passing a file descriptor is deprecated and may result in an error being thrown
3819in the future.
3820
3821## `fs.unlink(path, callback)`
3822<!-- YAML
3823added: v0.0.2
3824changes:
3825  - version: v10.0.0
3826    pr-url: https://github.com/nodejs/node/pull/12562
3827    description: The `callback` parameter is no longer optional. Not passing
3828                 it will throw a `TypeError` at runtime.
3829  - version: v7.6.0
3830    pr-url: https://github.com/nodejs/node/pull/10739
3831    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3832                 protocol. Support is currently still *experimental*.
3833  - version: v7.0.0
3834    pr-url: https://github.com/nodejs/node/pull/7897
3835    description: The `callback` parameter is no longer optional. Not passing
3836                 it will emit a deprecation warning with id DEP0013.
3837-->
3838
3839* `path` {string|Buffer|URL}
3840* `callback` {Function}
3841  * `err` {Error}
3842
3843Asynchronously removes a file or symbolic link. No arguments other than a
3844possible exception are given to the completion callback.
3845
3846```js
3847// Assuming that 'path/file.txt' is a regular file.
3848fs.unlink('path/file.txt', (err) => {
3849  if (err) throw err;
3850  console.log('path/file.txt was deleted');
3851});
3852```
3853
3854`fs.unlink()` will not work on a directory, empty or otherwise. To remove a
3855directory, use [`fs.rmdir()`][].
3856
3857See also: unlink(2).
3858
3859## `fs.unlinkSync(path)`
3860<!-- YAML
3861added: v0.1.21
3862changes:
3863  - version: v7.6.0
3864    pr-url: https://github.com/nodejs/node/pull/10739
3865    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3866                 protocol. Support is currently still *experimental*.
3867-->
3868
3869* `path` {string|Buffer|URL}
3870
3871Synchronous unlink(2). Returns `undefined`.
3872
3873## `fs.unwatchFile(filename[, listener])`
3874<!-- YAML
3875added: v0.1.31
3876-->
3877
3878* `filename` {string|Buffer|URL}
3879* `listener` {Function} Optional, a listener previously attached using
3880  `fs.watchFile()`
3881
3882Stop watching for changes on `filename`. If `listener` is specified, only that
3883particular listener is removed. Otherwise, *all* listeners are removed,
3884effectively stopping watching of `filename`.
3885
3886Calling `fs.unwatchFile()` with a filename that is not being watched is a
3887no-op, not an error.
3888
3889Using [`fs.watch()`][] is more efficient than `fs.watchFile()` and
3890`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`
3891and `fs.unwatchFile()` when possible.
3892
3893## `fs.utimes(path, atime, mtime, callback)`
3894<!-- YAML
3895added: v0.4.2
3896changes:
3897  - version: v10.0.0
3898    pr-url: https://github.com/nodejs/node/pull/12562
3899    description: The `callback` parameter is no longer optional. Not passing
3900                 it will throw a `TypeError` at runtime.
3901  - version: v8.0.0
3902    pr-url: https://github.com/nodejs/node/pull/11919
3903    description: "`NaN`, `Infinity`, and `-Infinity` are no longer valid time
3904                 specifiers."
3905  - version: v7.6.0
3906    pr-url: https://github.com/nodejs/node/pull/10739
3907    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3908                 protocol. Support is currently still *experimental*.
3909  - version: v7.0.0
3910    pr-url: https://github.com/nodejs/node/pull/7897
3911    description: The `callback` parameter is no longer optional. Not passing
3912                 it will emit a deprecation warning with id DEP0013.
3913  - version: v4.1.0
3914    pr-url: https://github.com/nodejs/node/pull/2387
3915    description: Numeric strings, `NaN` and `Infinity` are now allowed
3916                 time specifiers.
3917-->
3918
3919* `path` {string|Buffer|URL}
3920* `atime` {number|string|Date}
3921* `mtime` {number|string|Date}
3922* `callback` {Function}
3923  * `err` {Error}
3924
3925Change the file system timestamps of the object referenced by `path`.
3926
3927The `atime` and `mtime` arguments follow these rules:
3928
3929* Values can be either numbers representing Unix epoch time in seconds,
3930  `Date`s, or a numeric string like `'123456789.0'`.
3931* If the value can not be converted to a number, or is `NaN`, `Infinity` or
3932  `-Infinity`, an `Error` will be thrown.
3933
3934## `fs.utimesSync(path, atime, mtime)`
3935<!-- YAML
3936added: v0.4.2
3937changes:
3938  - version: v8.0.0
3939    pr-url: https://github.com/nodejs/node/pull/11919
3940    description: "`NaN`, `Infinity`, and `-Infinity` are no longer valid time
3941                 specifiers."
3942  - version: v7.6.0
3943    pr-url: https://github.com/nodejs/node/pull/10739
3944    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3945                 protocol. Support is currently still *experimental*.
3946  - version: v4.1.0
3947    pr-url: https://github.com/nodejs/node/pull/2387
3948    description: Numeric strings, `NaN` and `Infinity` are now allowed
3949                 time specifiers.
3950-->
3951
3952* `path` {string|Buffer|URL}
3953* `atime` {number|string|Date}
3954* `mtime` {number|string|Date}
3955
3956Returns `undefined`.
3957
3958For detailed information, see the documentation of the asynchronous version of
3959this API: [`fs.utimes()`][].
3960
3961## `fs.watch(filename[, options][, listener])`
3962<!-- YAML
3963added: v0.5.10
3964changes:
3965  - version: v7.6.0
3966    pr-url: https://github.com/nodejs/node/pull/10739
3967    description: The `filename` parameter can be a WHATWG `URL` object using
3968                 `file:` protocol. Support is currently still *experimental*.
3969  - version: v7.0.0
3970    pr-url: https://github.com/nodejs/node/pull/7831
3971    description: The passed `options` object will never be modified.
3972-->
3973
3974* `filename` {string|Buffer|URL}
3975* `options` {string|Object}
3976  * `persistent` {boolean} Indicates whether the process should continue to run
3977    as long as files are being watched. **Default:** `true`.
3978  * `recursive` {boolean} Indicates whether all subdirectories should be
3979    watched, or only the current directory. This applies when a directory is
3980    specified, and only on supported platforms (See [Caveats][]). **Default:**
3981    `false`.
3982  * `encoding` {string} Specifies the character encoding to be used for the
3983     filename passed to the listener. **Default:** `'utf8'`.
3984* `listener` {Function|undefined} **Default:** `undefined`
3985  * `eventType` {string}
3986  * `filename` {string|Buffer}
3987* Returns: {fs.FSWatcher}
3988
3989Watch for changes on `filename`, where `filename` is either a file or a
3990directory.
3991
3992The second argument is optional. If `options` is provided as a string, it
3993specifies the `encoding`. Otherwise `options` should be passed as an object.
3994
3995The listener callback gets two arguments `(eventType, filename)`. `eventType`
3996is either `'rename'` or `'change'`, and `filename` is the name of the file
3997which triggered the event.
3998
3999On most platforms, `'rename'` is emitted whenever a filename appears or
4000disappears in the directory.
4001
4002The listener callback is attached to the `'change'` event fired by
4003[`fs.FSWatcher`][], but it is not the same thing as the `'change'` value of
4004`eventType`.
4005
4006### Caveats
4007
4008<!--type=misc-->
4009
4010The `fs.watch` API is not 100% consistent across platforms, and is
4011unavailable in some situations.
4012
4013The recursive option is only supported on macOS and Windows.
4014
4015On Windows, no events will be emitted if the watched directory is moved or
4016renamed. An `EPERM` error is reported when the watched directory is deleted.
4017
4018#### Availability
4019
4020<!--type=misc-->
4021
4022This feature depends on the underlying operating system providing a way
4023to be notified of filesystem changes.
4024
4025* On Linux systems, this uses [`inotify(7)`][].
4026* On BSD systems, this uses [`kqueue(2)`][].
4027* On macOS, this uses [`kqueue(2)`][] for files and [`FSEvents`][] for
4028  directories.
4029* On SunOS systems (including Solaris and SmartOS), this uses [`event ports`][].
4030* On Windows systems, this feature depends on [`ReadDirectoryChangesW`][].
4031* On Aix systems, this feature depends on [`AHAFS`][], which must be enabled.
4032* On IBM i systems, this feature is not supported.
4033
4034If the underlying functionality is not available for some reason, then
4035`fs.watch()` will not be able to function and may thrown an exception.
4036For example, watching files or directories can be unreliable, and in some
4037cases impossible, on network file systems (NFS, SMB, etc) or host file systems
4038when using virtualization software such as Vagrant or Docker.
4039
4040It is still possible to use `fs.watchFile()`, which uses stat polling, but
4041this method is slower and less reliable.
4042
4043#### Inodes
4044
4045<!--type=misc-->
4046
4047On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and
4048watches the inode. If the watched path is deleted and recreated, it is assigned
4049a new inode. The watch will emit an event for the delete but will continue
4050watching the *original* inode. Events for the new inode will not be emitted.
4051This is expected behavior.
4052
4053AIX files retain the same inode for the lifetime of a file. Saving and closing a
4054watched file on AIX will result in two notifications (one for adding new
4055content, and one for truncation).
4056
4057#### Filename argument
4058
4059<!--type=misc-->
4060
4061Providing `filename` argument in the callback is only supported on Linux,
4062macOS, Windows, and AIX. Even on supported platforms, `filename` is not always
4063guaranteed to be provided. Therefore, don't assume that `filename` argument is
4064always provided in the callback, and have some fallback logic if it is `null`.
4065
4066```js
4067fs.watch('somedir', (eventType, filename) => {
4068  console.log(`event type is: ${eventType}`);
4069  if (filename) {
4070    console.log(`filename provided: ${filename}`);
4071  } else {
4072    console.log('filename not provided');
4073  }
4074});
4075```
4076
4077## `fs.watchFile(filename[, options], listener)`
4078<!-- YAML
4079added: v0.1.31
4080changes:
4081  - version: v10.5.0
4082    pr-url: https://github.com/nodejs/node/pull/20220
4083    description: The `bigint` option is now supported.
4084  - version: v7.6.0
4085    pr-url: https://github.com/nodejs/node/pull/10739
4086    description: The `filename` parameter can be a WHATWG `URL` object using
4087                 `file:` protocol. Support is currently still *experimental*.
4088-->
4089
4090* `filename` {string|Buffer|URL}
4091* `options` {Object}
4092  * `bigint` {boolean} **Default:** `false`
4093  * `persistent` {boolean} **Default:** `true`
4094  * `interval` {integer} **Default:** `5007`
4095* `listener` {Function}
4096  * `current` {fs.Stats}
4097  * `previous` {fs.Stats}
4098* Returns: {fs.StatWatcher}
4099
4100Watch for changes on `filename`. The callback `listener` will be called each
4101time the file is accessed.
4102
4103The `options` argument may be omitted. If provided, it should be an object. The
4104`options` object may contain a boolean named `persistent` that indicates
4105whether the process should continue to run as long as files are being watched.
4106The `options` object may specify an `interval` property indicating how often the
4107target should be polled in milliseconds.
4108
4109The `listener` gets two arguments the current stat object and the previous
4110stat object:
4111
4112```js
4113fs.watchFile('message.text', (curr, prev) => {
4114  console.log(`the current mtime is: ${curr.mtime}`);
4115  console.log(`the previous mtime was: ${prev.mtime}`);
4116});
4117```
4118
4119These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
4120the numeric values in these objects are specified as `BigInt`s.
4121
4122To be notified when the file was modified, not just accessed, it is necessary
4123to compare `curr.mtime` and `prev.mtime`.
4124
4125When an `fs.watchFile` operation results in an `ENOENT` error, it
4126will invoke the listener once, with all the fields zeroed (or, for dates, the
4127Unix Epoch). If the file is created later on, the listener will be called
4128again, with the latest stat objects. This is a change in functionality since
4129v0.10.
4130
4131Using [`fs.watch()`][] is more efficient than `fs.watchFile` and
4132`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and
4133`fs.unwatchFile` when possible.
4134
4135When a file being watched by `fs.watchFile()` disappears and reappears,
4136then the contents of `previous` in the second callback event (the file's
4137reappearance) will be the same as the contents of `previous` in the first
4138callback event (its disappearance).
4139
4140This happens when:
4141
4142* the file is deleted, followed by a restore
4143* the file is renamed and then renamed a second time back to its original name
4144
4145## `fs.write(fd, buffer[, offset[, length[, position]]], callback)`
4146<!-- YAML
4147added: v0.0.2
4148changes:
4149  - version: v10.10.0
4150    pr-url: https://github.com/nodejs/node/pull/22150
4151    description: The `buffer` parameter can now be any `TypedArray` or a
4152                 `DataView`
4153  - version: v10.0.0
4154    pr-url: https://github.com/nodejs/node/pull/12562
4155    description: The `callback` parameter is no longer optional. Not passing
4156                 it will throw a `TypeError` at runtime.
4157  - version: v7.4.0
4158    pr-url: https://github.com/nodejs/node/pull/10382
4159    description: The `buffer` parameter can now be a `Uint8Array`.
4160  - version: v7.2.0
4161    pr-url: https://github.com/nodejs/node/pull/7856
4162    description: The `offset` and `length` parameters are optional now.
4163  - version: v7.0.0
4164    pr-url: https://github.com/nodejs/node/pull/7897
4165    description: The `callback` parameter is no longer optional. Not passing
4166                 it will emit a deprecation warning with id DEP0013.
4167-->
4168
4169* `fd` {integer}
4170* `buffer` {Buffer|TypedArray|DataView}
4171* `offset` {integer}
4172* `length` {integer}
4173* `position` {integer}
4174* `callback` {Function}
4175  * `err` {Error}
4176  * `bytesWritten` {integer}
4177  * `buffer` {Buffer|TypedArray|DataView}
4178
4179Write `buffer` to the file specified by `fd`.
4180
4181`offset` determines the part of the buffer to be written, and `length` is
4182an integer specifying the number of bytes to write.
4183
4184`position` refers to the offset from the beginning of the file where this data
4185should be written. If `typeof position !== 'number'`, the data will be written
4186at the current position. See pwrite(2).
4187
4188The callback will be given three arguments `(err, bytesWritten, buffer)` where
4189`bytesWritten` specifies how many _bytes_ were written from `buffer`.
4190
4191If this method is invoked as its [`util.promisify()`][]ed version, it returns
4192a `Promise` for an `Object` with `bytesWritten` and `buffer` properties.
4193
4194It is unsafe to use `fs.write()` multiple times on the same file without waiting
4195for the callback. For this scenario, [`fs.createWriteStream()`][] is
4196recommended.
4197
4198On Linux, positional writes don't work when the file is opened in append mode.
4199The kernel ignores the position argument and always appends the data to
4200the end of the file.
4201
4202## `fs.write(fd, string[, position[, encoding]], callback)`
4203<!-- YAML
4204added: v0.11.5
4205changes:
4206  - version: v10.0.0
4207    pr-url: https://github.com/nodejs/node/pull/12562
4208    description: The `callback` parameter is no longer optional. Not passing
4209                 it will throw a `TypeError` at runtime.
4210  - version: v7.2.0
4211    pr-url: https://github.com/nodejs/node/pull/7856
4212    description: The `position` parameter is optional now.
4213  - version: v7.0.0
4214    pr-url: https://github.com/nodejs/node/pull/7897
4215    description: The `callback` parameter is no longer optional. Not passing
4216                 it will emit a deprecation warning with id DEP0013.
4217-->
4218
4219* `fd` {integer}
4220* `string` {string}
4221* `position` {integer}
4222* `encoding` {string} **Default:** `'utf8'`
4223* `callback` {Function}
4224  * `err` {Error}
4225  * `written` {integer}
4226  * `string` {string}
4227
4228Write `string` to the file specified by `fd`. If `string` is not a string, then
4229the value will be coerced to one.
4230
4231`position` refers to the offset from the beginning of the file where this data
4232should be written. If `typeof position !== 'number'` the data will be written at
4233the current position. See pwrite(2).
4234
4235`encoding` is the expected string encoding.
4236
4237The callback will receive the arguments `(err, written, string)` where `written`
4238specifies how many _bytes_ the passed string required to be written. Bytes
4239written is not necessarily the same as string characters written. See
4240[`Buffer.byteLength`][].
4241
4242It is unsafe to use `fs.write()` multiple times on the same file without waiting
4243for the callback. For this scenario, [`fs.createWriteStream()`][] is
4244recommended.
4245
4246On Linux, positional writes don't work when the file is opened in append mode.
4247The kernel ignores the position argument and always appends the data to
4248the end of the file.
4249
4250On Windows, if the file descriptor is connected to the console (e.g. `fd == 1`
4251or `stdout`) a string containing non-ASCII characters will not be rendered
4252properly by default, regardless of the encoding used.
4253It is possible to configure the console to render UTF-8 properly by changing the
4254active codepage with the `chcp 65001` command. See the [chcp][] docs for more
4255details.
4256
4257## `fs.writeFile(file, data[, options], callback)`
4258<!-- YAML
4259added: v0.1.29
4260changes:
4261  - version: v10.10.0
4262    pr-url: https://github.com/nodejs/node/pull/22150
4263    description: The `data` parameter can now be any `TypedArray` or a
4264                 `DataView`.
4265  - version: v10.0.0
4266    pr-url: https://github.com/nodejs/node/pull/12562
4267    description: The `callback` parameter is no longer optional. Not passing
4268                 it will throw a `TypeError` at runtime.
4269  - version: v7.4.0
4270    pr-url: https://github.com/nodejs/node/pull/10382
4271    description: The `data` parameter can now be a `Uint8Array`.
4272  - version: v7.0.0
4273    pr-url: https://github.com/nodejs/node/pull/7897
4274    description: The `callback` parameter is no longer optional. Not passing
4275                 it will emit a deprecation warning with id DEP0013.
4276  - version: v5.0.0
4277    pr-url: https://github.com/nodejs/node/pull/3163
4278    description: The `file` parameter can be a file descriptor now.
4279-->
4280
4281* `file` {string|Buffer|URL|integer} filename or file descriptor
4282* `data` {string|Buffer|TypedArray|DataView}
4283* `options` {Object|string}
4284  * `encoding` {string|null} **Default:** `'utf8'`
4285  * `mode` {integer} **Default:** `0o666`
4286  * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.
4287* `callback` {Function}
4288  * `err` {Error}
4289
4290When `file` is a filename, asynchronously writes data to the file, replacing the
4291file if it already exists.  `data` can be a string or a buffer.
4292
4293When `file` is a file descriptor, the behavior is similar to calling
4294`fs.write()` directly (which is recommended). See the notes below on using
4295a file descriptor.
4296
4297The `encoding` option is ignored if `data` is a buffer.
4298
4299```js
4300const data = new Uint8Array(Buffer.from('Hello Node.js'));
4301fs.writeFile('message.txt', data, (err) => {
4302  if (err) throw err;
4303  console.log('The file has been saved!');
4304});
4305```
4306
4307If `options` is a string, then it specifies the encoding:
4308
4309```js
4310fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
4311```
4312
4313It is unsafe to use `fs.writeFile()` multiple times on the same file without
4314waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is
4315recommended.
4316
4317### Using `fs.writeFile()` with file descriptors
4318
4319When `file` is a file descriptor, the behavior is almost identical to directly
4320calling `fs.write()` like:
4321
4322```js
4323fs.write(fd, Buffer.from(data, options.encoding), callback);
4324```
4325
4326The difference from directly calling `fs.write()` is that under some unusual
4327conditions, `fs.write()` may write only part of the buffer and will need to be
4328retried to write the remaining data, whereas `fs.writeFile()` will retry until
4329the data is entirely written (or an error occurs).
4330
4331The implications of this are a common source of confusion. In
4332the file descriptor case, the file is not replaced! The data is not necessarily
4333written to the beginning of the file, and the file's original data may remain
4334before and/or after the newly written data.
4335
4336For example, if `fs.writeFile()` is called twice in a row, first to write the
4337string `'Hello'`, then to write the string `', World'`, the file would contain
4338`'Hello, World'`, and might contain some of the file's original data (depending
4339on the size of the original file, and the position of the file descriptor). If
4340a file name had been used instead of a descriptor, the file would be guaranteed
4341to contain only `', World'`.
4342
4343## `fs.writeFileSync(file, data[, options])`
4344<!-- YAML
4345added: v0.1.29
4346changes:
4347  - version: v10.10.0
4348    pr-url: https://github.com/nodejs/node/pull/22150
4349    description: The `data` parameter can now be any `TypedArray` or a
4350                 `DataView`.
4351  - version: v7.4.0
4352    pr-url: https://github.com/nodejs/node/pull/10382
4353    description: The `data` parameter can now be a `Uint8Array`.
4354  - version: v5.0.0
4355    pr-url: https://github.com/nodejs/node/pull/3163
4356    description: The `file` parameter can be a file descriptor now.
4357-->
4358
4359* `file` {string|Buffer|URL|integer} filename or file descriptor
4360* `data` {string|Buffer|TypedArray|DataView}
4361* `options` {Object|string}
4362  * `encoding` {string|null} **Default:** `'utf8'`
4363  * `mode` {integer} **Default:** `0o666`
4364  * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.
4365
4366Returns `undefined`.
4367
4368For detailed information, see the documentation of the asynchronous version of
4369this API: [`fs.writeFile()`][].
4370
4371## `fs.writeSync(fd, buffer[, offset[, length[, position]]])`
4372<!-- YAML
4373added: v0.1.21
4374changes:
4375  - version: v10.10.0
4376    pr-url: https://github.com/nodejs/node/pull/22150
4377    description: The `buffer` parameter can now be any `TypedArray` or a
4378                 `DataView`.
4379  - version: v7.4.0
4380    pr-url: https://github.com/nodejs/node/pull/10382
4381    description: The `buffer` parameter can now be a `Uint8Array`.
4382  - version: v7.2.0
4383    pr-url: https://github.com/nodejs/node/pull/7856
4384    description: The `offset` and `length` parameters are optional now.
4385-->
4386
4387* `fd` {integer}
4388* `buffer` {Buffer|TypedArray|DataView}
4389* `offset` {integer}
4390* `length` {integer}
4391* `position` {integer}
4392* Returns: {number} The number of bytes written.
4393
4394For detailed information, see the documentation of the asynchronous version of
4395this API: [`fs.write(fd, buffer...)`][].
4396
4397## `fs.writeSync(fd, string[, position[, encoding]])`
4398<!-- YAML
4399added: v0.11.5
4400changes:
4401  - version: v7.2.0
4402    pr-url: https://github.com/nodejs/node/pull/7856
4403    description: The `position` parameter is optional now.
4404-->
4405
4406* `fd` {integer}
4407* `string` {string}
4408* `position` {integer}
4409* `encoding` {string}
4410* Returns: {number} The number of bytes written.
4411
4412For detailed information, see the documentation of the asynchronous version of
4413this API: [`fs.write(fd, string...)`][].
4414
4415## `fs.writev(fd, buffers[, position], callback)`
4416<!-- YAML
4417added: v12.9.0
4418-->
4419
4420* `fd` {integer}
4421* `buffers` {ArrayBufferView[]}
4422* `position` {integer}
4423* `callback` {Function}
4424  * `err` {Error}
4425  * `bytesWritten` {integer}
4426  * `buffers` {ArrayBufferView[]}
4427
4428Write an array of `ArrayBufferView`s to the file specified by `fd` using
4429`writev()`.
4430
4431`position` is the offset from the beginning of the file where this data
4432should be written. If `typeof position !== 'number'`, the data will be written
4433at the current position.
4434
4435The callback will be given three arguments: `err`, `bytesWritten`, and
4436`buffers`. `bytesWritten` is how many bytes were written from `buffers`.
4437
4438If this method is [`util.promisify()`][]ed, it returns a `Promise` for an
4439`Object` with `bytesWritten` and `buffers` properties.
4440
4441It is unsafe to use `fs.writev()` multiple times on the same file without
4442waiting for the callback. For this scenario, use [`fs.createWriteStream()`][].
4443
4444On Linux, positional writes don't work when the file is opened in append mode.
4445The kernel ignores the position argument and always appends the data to
4446the end of the file.
4447
4448## `fs.writevSync(fd, buffers[, position])`
4449<!-- YAML
4450added: v12.9.0
4451-->
4452
4453* `fd` {integer}
4454* `buffers` {ArrayBufferView[]}
4455* `position` {integer}
4456* Returns: {number} The number of bytes written.
4457
4458For detailed information, see the documentation of the asynchronous version of
4459this API: [`fs.writev()`][].
4460
4461## `fs` Promises API
4462
4463The `fs.promises` API provides an alternative set of asynchronous file system
4464methods that return `Promise` objects rather than using callbacks. The
4465API is accessible via `require('fs').promises`.
4466
4467### Class: `FileHandle`
4468<!-- YAML
4469added: v10.0.0
4470-->
4471
4472A `FileHandle` object is a wrapper for a numeric file descriptor.
4473Instances of `FileHandle` are distinct from numeric file descriptors
4474in that they provide an object oriented API for working with files.
4475
4476If a `FileHandle` is not closed using the
4477`filehandle.close()` method, it might automatically close the file descriptor
4478and will emit a process warning, thereby helping to prevent memory leaks.
4479Please do not rely on this behavior because it is unreliable and
4480the file may not be closed. Instead, always explicitly close `FileHandle`s.
4481Node.js may change this behavior in the future.
4482
4483Instances of the `FileHandle` object are created internally by the
4484`fsPromises.open()` method.
4485
4486Unlike the callback-based API (`fs.fstat()`, `fs.fchown()`, `fs.fchmod()`, and
4487so on), a numeric file descriptor is not used by the promise-based API. Instead,
4488the promise-based API uses the `FileHandle` class in order to help avoid
4489accidental leaking of unclosed file descriptors after a `Promise` is resolved or
4490rejected.
4491
4492#### `filehandle.appendFile(data, options)`
4493<!-- YAML
4494added: v10.0.0
4495-->
4496
4497* `data` {string|Buffer}
4498* `options` {Object|string}
4499  * `encoding` {string|null} **Default:** `'utf8'`
4500* Returns: {Promise}
4501
4502Alias of [`filehandle.writeFile()`][].
4503
4504When operating on file handles, the mode cannot be changed from what it was set
4505to with [`fsPromises.open()`][]. Therefore, this is equivalent to
4506[`filehandle.writeFile()`][].
4507
4508#### `filehandle.chmod(mode)`
4509<!-- YAML
4510added: v10.0.0
4511-->
4512
4513* `mode` {integer}
4514* Returns: {Promise}
4515
4516Modifies the permissions on the file. The `Promise` is resolved with no
4517arguments upon success.
4518
4519#### `filehandle.chown(uid, gid)`
4520<!-- YAML
4521added: v10.0.0
4522-->
4523
4524* `uid` {integer}
4525* `gid` {integer}
4526* Returns: {Promise}
4527
4528Changes the ownership of the file then resolves the `Promise` with no arguments
4529upon success.
4530
4531#### `filehandle.close()`
4532<!-- YAML
4533added: v10.0.0
4534-->
4535
4536* Returns: {Promise} A `Promise` that will be resolved once the underlying
4537  file descriptor is closed, or will be rejected if an error occurs while
4538  closing.
4539
4540Closes the file descriptor.
4541
4542```js
4543const fsPromises = require('fs').promises;
4544async function openAndClose() {
4545  let filehandle;
4546  try {
4547    filehandle = await fsPromises.open('thefile.txt', 'r');
4548  } finally {
4549    if (filehandle !== undefined)
4550      await filehandle.close();
4551  }
4552}
4553```
4554
4555#### `filehandle.datasync()`
4556<!-- YAML
4557added: v10.0.0
4558-->
4559
4560* Returns: {Promise}
4561
4562Asynchronous fdatasync(2). The `Promise` is resolved with no arguments upon
4563success.
4564
4565#### `filehandle.fd`
4566<!-- YAML
4567added: v10.0.0
4568-->
4569
4570* {number} The numeric file descriptor managed by the `FileHandle` object.
4571
4572#### `filehandle.read(buffer, offset, length, position)`
4573<!-- YAML
4574added: v10.0.0
4575-->
4576
4577* `buffer` {Buffer|Uint8Array}
4578* `offset` {integer}
4579* `length` {integer}
4580* `position` {integer}
4581* Returns: {Promise}
4582
4583Read data from the file.
4584
4585`buffer` is the buffer that the data will be written to.
4586
4587`offset` is the offset in the buffer to start writing at.
4588
4589`length` is an integer specifying the number of bytes to read.
4590
4591`position` is an argument specifying where to begin reading from in the file.
4592If `position` is `null`, data will be read from the current file position,
4593and the file position will be updated.
4594If `position` is an integer, the file position will remain unchanged.
4595
4596Following successful read, the `Promise` is resolved with an object with a
4597`bytesRead` property specifying the number of bytes read, and a `buffer`
4598property that is a reference to the passed in `buffer` argument.
4599
4600#### `filehandle.read(options)`
4601<!-- YAML
4602added: v12.17.0
4603-->
4604* `options` {Object}
4605  * `buffer` {Buffer|Uint8Array} **Default:** `Buffer.alloc(16384)`
4606  * `offset` {integer} **Default:** `0`
4607  * `length` {integer} **Default:** `buffer.length`
4608  * `position` {integer} **Default:** `null`
4609* Returns: {Promise}
4610
4611#### `filehandle.readFile(options)`
4612<!-- YAML
4613added: v10.0.0
4614-->
4615
4616* `options` {Object|string}
4617  * `encoding` {string|null} **Default:** `null`
4618* Returns: {Promise}
4619
4620Asynchronously reads the entire contents of a file.
4621
4622The `Promise` is resolved with the contents of the file. If no encoding is
4623specified (using `options.encoding`), the data is returned as a `Buffer`
4624object. Otherwise, the data will be a string.
4625
4626If `options` is a string, then it specifies the encoding.
4627
4628The `FileHandle` has to support reading.
4629
4630If one or more `filehandle.read()` calls are made on a file handle and then a
4631`filehandle.readFile()` call is made, the data will be read from the current
4632position till the end of the file. It doesn't always read from the beginning
4633of the file.
4634
4635#### `filehandle.readv(buffers[, position])`
4636<!-- YAML
4637added: v12.17.0
4638-->
4639
4640* `buffers` {ArrayBufferView[]}
4641* `position` {integer}
4642* Returns: {Promise}
4643
4644Read from a file and write to an array of `ArrayBufferView`s
4645
4646The `Promise` is resolved with an object containing a `bytesRead` property
4647identifying the number of bytes read, and a `buffers` property containing
4648a reference to the `buffers` input.
4649
4650`position` is the offset from the beginning of the file where this data
4651should be read from. If `typeof position !== 'number'`, the data will be read
4652from the current position.
4653
4654#### `filehandle.stat([options])`
4655<!-- YAML
4656added: v10.0.0
4657changes:
4658  - version: v10.5.0
4659    pr-url: https://github.com/nodejs/node/pull/20220
4660    description: Accepts an additional `options` object to specify whether
4661                 the numeric values returned should be bigint.
4662-->
4663
4664* `options` {Object}
4665  * `bigint` {boolean} Whether the numeric values in the returned
4666    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
4667* Returns: {Promise}
4668
4669Retrieves the [`fs.Stats`][] for the file.
4670
4671#### `filehandle.sync()`
4672<!-- YAML
4673added: v10.0.0
4674-->
4675
4676* Returns: {Promise}
4677
4678Asynchronous fsync(2). The `Promise` is resolved with no arguments upon
4679success.
4680
4681#### `filehandle.truncate(len)`
4682<!-- YAML
4683added: v10.0.0
4684-->
4685
4686* `len` {integer} **Default:** `0`
4687* Returns: {Promise}
4688
4689Truncates the file then resolves the `Promise` with no arguments upon success.
4690
4691If the file was larger than `len` bytes, only the first `len` bytes will be
4692retained in the file.
4693
4694For example, the following program retains only the first four bytes of the
4695file:
4696
4697```js
4698const fs = require('fs');
4699const fsPromises = fs.promises;
4700
4701console.log(fs.readFileSync('temp.txt', 'utf8'));
4702// Prints: Node.js
4703
4704async function doTruncate() {
4705  let filehandle = null;
4706  try {
4707    filehandle = await fsPromises.open('temp.txt', 'r+');
4708    await filehandle.truncate(4);
4709  } finally {
4710    if (filehandle) {
4711      // Close the file if it is opened.
4712      await filehandle.close();
4713    }
4714  }
4715  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node
4716}
4717
4718doTruncate().catch(console.error);
4719```
4720
4721If the file previously was shorter than `len` bytes, it is extended, and the
4722extended part is filled with null bytes (`'\0'`):
4723
4724```js
4725const fs = require('fs');
4726const fsPromises = fs.promises;
4727
4728console.log(fs.readFileSync('temp.txt', 'utf8'));
4729// Prints: Node.js
4730
4731async function doTruncate() {
4732  let filehandle = null;
4733  try {
4734    filehandle = await fsPromises.open('temp.txt', 'r+');
4735    await filehandle.truncate(10);
4736  } finally {
4737    if (filehandle) {
4738      // Close the file if it is opened.
4739      await filehandle.close();
4740    }
4741  }
4742  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\0\0\0
4743}
4744
4745doTruncate().catch(console.error);
4746```
4747
4748The last three bytes are null bytes (`'\0'`), to compensate the over-truncation.
4749
4750#### `filehandle.utimes(atime, mtime)`
4751<!-- YAML
4752added: v10.0.0
4753-->
4754
4755* `atime` {number|string|Date}
4756* `mtime` {number|string|Date}
4757* Returns: {Promise}
4758
4759Change the file system timestamps of the object referenced by the `FileHandle`
4760then resolves the `Promise` with no arguments upon success.
4761
4762This function does not work on AIX versions before 7.1, it will resolve the
4763`Promise` with an error using code `UV_ENOSYS`.
4764
4765#### `filehandle.write(buffer[, offset[, length[, position]]])`
4766<!-- YAML
4767added: v10.0.0
4768-->
4769
4770* `buffer` {Buffer|Uint8Array}
4771* `offset` {integer}
4772* `length` {integer}
4773* `position` {integer}
4774* Returns: {Promise}
4775
4776Write `buffer` to the file.
4777
4778The `Promise` is resolved with an object containing a `bytesWritten` property
4779identifying the number of bytes written, and a `buffer` property containing
4780a reference to the `buffer` written.
4781
4782`offset` determines the part of the buffer to be written, and `length` is
4783an integer specifying the number of bytes to write.
4784
4785`position` refers to the offset from the beginning of the file where this data
4786should be written. If `typeof position !== 'number'`, the data will be written
4787at the current position. See pwrite(2).
4788
4789It is unsafe to use `filehandle.write()` multiple times on the same file
4790without waiting for the `Promise` to be resolved (or rejected). For this
4791scenario, use [`fs.createWriteStream()`][].
4792
4793On Linux, positional writes do not work when the file is opened in append mode.
4794The kernel ignores the position argument and always appends the data to
4795the end of the file.
4796
4797#### `filehandle.write(string[, position[, encoding]])`
4798<!-- YAML
4799added: v10.0.0
4800-->
4801
4802* `string` {string}
4803* `position` {integer}
4804* `encoding` {string} **Default:** `'utf8'`
4805* Returns: {Promise}
4806
4807Write `string` to the file. If `string` is not a string, then
4808the value will be coerced to one.
4809
4810The `Promise` is resolved with an object containing a `bytesWritten` property
4811identifying the number of bytes written, and a `buffer` property containing
4812a reference to the `string` written.
4813
4814`position` refers to the offset from the beginning of the file where this data
4815should be written. If the type of `position` is not a `number` the data
4816will be written at the current position. See pwrite(2).
4817
4818`encoding` is the expected string encoding.
4819
4820It is unsafe to use `filehandle.write()` multiple times on the same file
4821without waiting for the `Promise` to be resolved (or rejected). For this
4822scenario, use [`fs.createWriteStream()`][].
4823
4824On Linux, positional writes do not work when the file is opened in append mode.
4825The kernel ignores the position argument and always appends the data to
4826the end of the file.
4827
4828#### `filehandle.writeFile(data, options)`
4829<!-- YAML
4830added: v10.0.0
4831-->
4832
4833* `data` {string|Buffer|Uint8Array}
4834* `options` {Object|string}
4835  * `encoding` {string|null} **Default:** `'utf8'`
4836* Returns: {Promise}
4837
4838Asynchronously writes data to a file, replacing the file if it already exists.
4839`data` can be a string or a buffer. The `Promise` will be resolved with no
4840arguments upon success.
4841
4842The `encoding` option is ignored if `data` is a buffer.
4843
4844If `options` is a string, then it specifies the encoding.
4845
4846The `FileHandle` has to support writing.
4847
4848It is unsafe to use `filehandle.writeFile()` multiple times on the same file
4849without waiting for the `Promise` to be resolved (or rejected).
4850
4851If one or more `filehandle.write()` calls are made on a file handle and then a
4852`filehandle.writeFile()` call is made, the data will be written from the
4853current position till the end of the file. It doesn't always write from the
4854beginning of the file.
4855
4856#### `filehandle.writev(buffers[, position])`
4857<!-- YAML
4858added: v12.9.0
4859-->
4860
4861* `buffers` {ArrayBufferView[]}
4862* `position` {integer}
4863* Returns: {Promise}
4864
4865Write an array of `ArrayBufferView`s to the file.
4866
4867The `Promise` is resolved with an object containing a `bytesWritten` property
4868identifying the number of bytes written, and a `buffers` property containing
4869a reference to the `buffers` input.
4870
4871`position` is the offset from the beginning of the file where this data
4872should be written. If `typeof position !== 'number'`, the data will be written
4873at the current position.
4874
4875It is unsafe to call `writev()` multiple times on the same file without waiting
4876for the previous operation to complete.
4877
4878On Linux, positional writes don't work when the file is opened in append mode.
4879The kernel ignores the position argument and always appends the data to
4880the end of the file.
4881
4882### `fsPromises.access(path[, mode])`
4883<!-- YAML
4884added: v10.0.0
4885-->
4886
4887* `path` {string|Buffer|URL}
4888* `mode` {integer} **Default:** `fs.constants.F_OK`
4889* Returns: {Promise}
4890
4891Tests a user's permissions for the file or directory specified by `path`.
4892The `mode` argument is an optional integer that specifies the accessibility
4893checks to be performed. Check [File access constants][] for possible values
4894of `mode`. It is possible to create a mask consisting of the bitwise OR of
4895two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
4896
4897If the accessibility check is successful, the `Promise` is resolved with no
4898value. If any of the accessibility checks fail, the `Promise` is rejected
4899with an `Error` object. The following example checks if the file
4900`/etc/passwd` can be read and written by the current process.
4901
4902```js
4903const fs = require('fs');
4904const fsPromises = fs.promises;
4905
4906fsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK)
4907  .then(() => console.log('can access'))
4908  .catch(() => console.error('cannot access'));
4909```
4910
4911Using `fsPromises.access()` to check for the accessibility of a file before
4912calling `fsPromises.open()` is not recommended. Doing so introduces a race
4913condition, since other processes may change the file's state between the two
4914calls. Instead, user code should open/read/write the file directly and handle
4915the error raised if the file is not accessible.
4916
4917### `fsPromises.appendFile(path, data[, options])`
4918<!-- YAML
4919added: v10.0.0
4920-->
4921
4922* `path` {string|Buffer|URL|FileHandle} filename or `FileHandle`
4923* `data` {string|Buffer}
4924* `options` {Object|string}
4925  * `encoding` {string|null} **Default:** `'utf8'`
4926  * `mode` {integer} **Default:** `0o666`
4927  * `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
4928* Returns: {Promise}
4929
4930Asynchronously append data to a file, creating the file if it does not yet
4931exist. `data` can be a string or a [`Buffer`][]. The `Promise` will be
4932resolved with no arguments upon success.
4933
4934If `options` is a string, then it specifies the encoding.
4935
4936The `path` may be specified as a `FileHandle` that has been opened
4937for appending (using `fsPromises.open()`).
4938
4939### `fsPromises.chmod(path, mode)`
4940<!-- YAML
4941added: v10.0.0
4942-->
4943
4944* `path` {string|Buffer|URL}
4945* `mode` {string|integer}
4946* Returns: {Promise}
4947
4948Changes the permissions of a file then resolves the `Promise` with no
4949arguments upon succces.
4950
4951### `fsPromises.chown(path, uid, gid)`
4952<!-- YAML
4953added: v10.0.0
4954-->
4955
4956* `path` {string|Buffer|URL}
4957* `uid` {integer}
4958* `gid` {integer}
4959* Returns: {Promise}
4960
4961Changes the ownership of a file then resolves the `Promise` with no arguments
4962upon success.
4963
4964### `fsPromises.copyFile(src, dest[, flags])`
4965<!-- YAML
4966added: v10.0.0
4967changes:
4968  - version: v14.0.0
4969    pr-url: https://github.com/nodejs/node/pull/27044
4970    description: Changed 'flags' argument to 'mode' and imposed
4971                 stricter type validation.
4972-->
4973
4974* `src` {string|Buffer|URL} source filename to copy
4975* `dest` {string|Buffer|URL} destination filename of the copy operation
4976* `flags` {number} modifiers for copy operation. **Default:** `0`.
4977* Returns: {Promise}
4978
4979Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
4980already exists. The `Promise` will be resolved with no arguments upon success.
4981
4982Node.js makes no guarantees about the atomicity of the copy operation. If an
4983error occurs after the destination file has been opened for writing, Node.js
4984will attempt to remove the destination.
4985
4986`flags` is an optional integer that specifies the behavior
4987of the copy operation. It is possible to create a mask consisting of the bitwise
4988OR of two or more values (e.g.
4989`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
4990
4991* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
4992exists.
4993* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
4994copy-on-write reflink. If the platform does not support copy-on-write, then a
4995fallback copy mechanism is used.
4996* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
4997create a copy-on-write reflink. If the platform does not support copy-on-write,
4998then the operation will fail.
4999
5000```js
5001const fsPromises = require('fs').promises;
5002
5003// destination.txt will be created or overwritten by default.
5004fsPromises.copyFile('source.txt', 'destination.txt')
5005  .then(() => console.log('source.txt was copied to destination.txt'))
5006  .catch(() => console.log('The file could not be copied'));
5007```
5008
5009If the third argument is a number, then it specifies `flags`:
5010
5011```js
5012const fs = require('fs');
5013const fsPromises = fs.promises;
5014const { COPYFILE_EXCL } = fs.constants;
5015
5016// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
5017fsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL)
5018  .then(() => console.log('source.txt was copied to destination.txt'))
5019  .catch(() => console.log('The file could not be copied'));
5020```
5021
5022### `fsPromises.lchmod(path, mode)`
5023<!-- YAML
5024deprecated: v10.0.0
5025-->
5026
5027* `path` {string|Buffer|URL}
5028* `mode` {integer}
5029* Returns: {Promise}
5030
5031Changes the permissions on a symbolic link then resolves the `Promise` with
5032no arguments upon success. This method is only implemented on macOS.
5033
5034### `fsPromises.lchown(path, uid, gid)`
5035<!-- YAML
5036added: v10.0.0
5037changes:
5038  - version: v10.6.0
5039    pr-url: https://github.com/nodejs/node/pull/21498
5040    description: This API is no longer deprecated.
5041-->
5042
5043* `path` {string|Buffer|URL}
5044* `uid` {integer}
5045* `gid` {integer}
5046* Returns: {Promise}
5047
5048Changes the ownership on a symbolic link then resolves the `Promise` with
5049no arguments upon success.
5050
5051### `fsPromises.lutimes(path, atime, mtime)`
5052<!-- YAML
5053added: v12.19.0
5054-->
5055
5056* `path` {string|Buffer|URL}
5057* `atime` {number|string|Date}
5058* `mtime` {number|string|Date}
5059* Returns: {Promise}
5060
5061Changes the access and modification times of a file in the same way as
5062[`fsPromises.utimes()`][], with the difference that if the path refers to a
5063symbolic link, then the link is not dereferenced: instead, the timestamps of
5064the symbolic link itself are changed.
5065
5066Upon success, the `Promise` is resolved without arguments.
5067
5068### `fsPromises.link(existingPath, newPath)`
5069<!-- YAML
5070added: v10.0.0
5071-->
5072
5073* `existingPath` {string|Buffer|URL}
5074* `newPath` {string|Buffer|URL}
5075* Returns: {Promise}
5076
5077Asynchronous link(2). The `Promise` is resolved with no arguments upon success.
5078
5079### `fsPromises.lstat(path[, options])`
5080<!-- YAML
5081added: v10.0.0
5082changes:
5083  - version: v10.5.0
5084    pr-url: https://github.com/nodejs/node/pull/20220
5085    description: Accepts an additional `options` object to specify whether
5086                 the numeric values returned should be bigint.
5087-->
5088
5089* `path` {string|Buffer|URL}
5090* `options` {Object}
5091  * `bigint` {boolean} Whether the numeric values in the returned
5092    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
5093* Returns: {Promise}
5094
5095Asynchronous lstat(2). The `Promise` is resolved with the [`fs.Stats`][] object
5096for the given symbolic link `path`.
5097
5098### `fsPromises.mkdir(path[, options])`
5099<!-- YAML
5100added: v10.0.0
5101-->
5102
5103* `path` {string|Buffer|URL}
5104* `options` {Object|integer}
5105  * `recursive` {boolean} **Default:** `false`
5106  * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
5107* Returns: {Promise}
5108
5109Asynchronously creates a directory then resolves the `Promise` with either no
5110arguments, or the first directory path created if `recursive` is `true`.
5111
5112The optional `options` argument can be an integer specifying mode (permission
5113and sticky bits), or an object with a `mode` property and a `recursive`
5114property indicating whether parent directories should be created. Calling
5115`fsPromises.mkdir()` when `path` is a directory that exists results in a
5116rejection only when `recursive` is false.
5117
5118### `fsPromises.mkdtemp(prefix[, options])`
5119<!-- YAML
5120added: v10.0.0
5121-->
5122
5123* `prefix` {string}
5124* `options` {string|Object}
5125  * `encoding` {string} **Default:** `'utf8'`
5126* Returns: {Promise}
5127
5128Creates a unique temporary directory and resolves the `Promise` with the created
5129directory path. A unique directory name is generated by appending six random
5130characters to the end of the provided `prefix`. Due to platform
5131inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
5132notably the BSDs, can return more than six random characters, and replace
5133trailing `X` characters in `prefix` with random characters.
5134
5135The optional `options` argument can be a string specifying an encoding, or an
5136object with an `encoding` property specifying the character encoding to use.
5137
5138```js
5139fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))
5140  .catch(console.error);
5141```
5142
5143The `fsPromises.mkdtemp()` method will append the six randomly selected
5144characters directly to the `prefix` string. For instance, given a directory
5145`/tmp`, if the intention is to create a temporary directory *within* `/tmp`, the
5146`prefix` must end with a trailing platform-specific path separator
5147(`require('path').sep`).
5148
5149### `fsPromises.open(path, flags[, mode])`
5150<!-- YAML
5151added: v10.0.0
5152changes:
5153  - version: v11.1.0
5154    pr-url: https://github.com/nodejs/node/pull/23767
5155    description: The `flags` argument is now optional and defaults to `'r'`.
5156-->
5157
5158* `path` {string|Buffer|URL}
5159* `flags` {string|number} See [support of file system `flags`][].
5160  **Default:** `'r'`.
5161* `mode` {string|integer} **Default:** `0o666` (readable and writable)
5162* Returns: {Promise}
5163
5164Asynchronous file open that returns a `Promise` that, when resolved, yields a
5165`FileHandle` object. See open(2).
5166
5167`mode` sets the file mode (permission and sticky bits), but only if the file was
5168created.
5169
5170Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
5171by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains
5172a colon, Node.js will open a file system stream, as described by
5173[this MSDN page][MSDN-Using-Streams].
5174
5175### `fsPromises.opendir(path[, options])`
5176<!-- YAML
5177added: v12.12.0
5178changes:
5179  - version: v12.16.0
5180    pr-url: https://github.com/nodejs/node/pull/30114
5181    description: The `bufferSize` option was introduced.
5182-->
5183
5184* `path` {string|Buffer|URL}
5185* `options` {Object}
5186  * `encoding` {string|null} **Default:** `'utf8'`
5187  * `bufferSize` {number} Number of directory entries that are buffered
5188    internally when reading from the directory. Higher values lead to better
5189    performance but higher memory usage. **Default:** `32`
5190* Returns: {Promise} containing {fs.Dir}
5191
5192Asynchronously open a directory. See opendir(3).
5193
5194Creates an [`fs.Dir`][], which contains all further functions for reading from
5195and cleaning up the directory.
5196
5197The `encoding` option sets the encoding for the `path` while opening the
5198directory and subsequent read operations.
5199
5200Example using async iteration:
5201
5202```js
5203const fs = require('fs');
5204
5205async function print(path) {
5206  const dir = await fs.promises.opendir(path);
5207  for await (const dirent of dir) {
5208    console.log(dirent.name);
5209  }
5210}
5211print('./').catch(console.error);
5212```
5213
5214### `fsPromises.readdir(path[, options])`
5215<!-- YAML
5216added: v10.0.0
5217changes:
5218  - version: v10.11.0
5219    pr-url: https://github.com/nodejs/node/pull/22020
5220    description: New option `withFileTypes` was added.
5221-->
5222
5223* `path` {string|Buffer|URL}
5224* `options` {string|Object}
5225  * `encoding` {string} **Default:** `'utf8'`
5226  * `withFileTypes` {boolean} **Default:** `false`
5227* Returns: {Promise}
5228
5229Reads the contents of a directory then resolves the `Promise` with an array
5230of the names of the files in the directory excluding `'.'` and `'..'`.
5231
5232The optional `options` argument can be a string specifying an encoding, or an
5233object with an `encoding` property specifying the character encoding to use for
5234the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
5235will be passed as `Buffer` objects.
5236
5237If `options.withFileTypes` is set to `true`, the resolved array will contain
5238[`fs.Dirent`][] objects.
5239
5240```js
5241const fs = require('fs');
5242
5243async function print(path) {
5244  const files = await fs.promises.readdir(path);
5245  for (const file of files) {
5246    console.log(file);
5247  }
5248}
5249print('./').catch(console.error);
5250```
5251
5252### `fsPromises.readFile(path[, options])`
5253<!-- YAML
5254added: v10.0.0
5255-->
5256
5257* `path` {string|Buffer|URL|FileHandle} filename or `FileHandle`
5258* `options` {Object|string}
5259  * `encoding` {string|null} **Default:** `null`
5260  * `flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.
5261* Returns: {Promise}
5262
5263Asynchronously reads the entire contents of a file.
5264
5265The `Promise` is resolved with the contents of the file. If no encoding is
5266specified (using `options.encoding`), the data is returned as a `Buffer`
5267object. Otherwise, the data will be a string.
5268
5269If `options` is a string, then it specifies the encoding.
5270
5271When the `path` is a directory, the behavior of `fsPromises.readFile()` is
5272platform-specific. On macOS, Linux, and Windows, the promise will be rejected
5273with an error. On FreeBSD, a representation of the directory's contents will be
5274returned.
5275
5276Any specified `FileHandle` has to support reading.
5277
5278### `fsPromises.readlink(path[, options])`
5279<!-- YAML
5280added: v10.0.0
5281-->
5282
5283* `path` {string|Buffer|URL}
5284* `options` {string|Object}
5285  * `encoding` {string} **Default:** `'utf8'`
5286* Returns: {Promise}
5287
5288Asynchronous readlink(2). The `Promise` is resolved with the `linkString` upon
5289success.
5290
5291The optional `options` argument can be a string specifying an encoding, or an
5292object with an `encoding` property specifying the character encoding to use for
5293the link path returned. If the `encoding` is set to `'buffer'`, the link path
5294returned will be passed as a `Buffer` object.
5295
5296### `fsPromises.realpath(path[, options])`
5297<!-- YAML
5298added: v10.0.0
5299-->
5300
5301* `path` {string|Buffer|URL}
5302* `options` {string|Object}
5303  * `encoding` {string} **Default:** `'utf8'`
5304* Returns: {Promise}
5305
5306Determines the actual location of `path` using the same semantics as the
5307`fs.realpath.native()` function then resolves the `Promise` with the resolved
5308path.
5309
5310Only paths that can be converted to UTF8 strings are supported.
5311
5312The optional `options` argument can be a string specifying an encoding, or an
5313object with an `encoding` property specifying the character encoding to use for
5314the path. If the `encoding` is set to `'buffer'`, the path returned will be
5315passed as a `Buffer` object.
5316
5317On Linux, when Node.js is linked against musl libc, the procfs file system must
5318be mounted on `/proc` in order for this function to work. Glibc does not have
5319this restriction.
5320
5321### `fsPromises.rename(oldPath, newPath)`
5322<!-- YAML
5323added: v10.0.0
5324-->
5325
5326* `oldPath` {string|Buffer|URL}
5327* `newPath` {string|Buffer|URL}
5328* Returns: {Promise}
5329
5330Renames `oldPath` to `newPath` and resolves the `Promise` with no arguments
5331upon success.
5332
5333### `fsPromises.rmdir(path[, options])`
5334<!-- YAML
5335added: v10.0.0
5336changes:
5337  - version: v12.16.0
5338    pr-url: https://github.com/nodejs/node/pull/30644
5339    description: The `maxBusyTries` option is renamed to `maxRetries`, and its
5340                 default is 0. The `emfileWait` option has been removed, and
5341                 `EMFILE` errors use the same retry logic as other errors. The
5342                 `retryDelay` option is now supported. `ENFILE` errors are now
5343                 retried.
5344  - version: v12.10.0
5345    pr-url: https://github.com/nodejs/node/pull/29168
5346    description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
5347                  now supported.
5348-->
5349
5350> Stability: 1 - Recursive removal is experimental.
5351
5352* `path` {string|Buffer|URL}
5353* `options` {Object}
5354  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
5355  `EPERM` error is encountered, Node.js will retry the operation with a linear
5356  backoff wait of `retryDelay` ms longer on each try. This option represents the
5357  number of retries. This option is ignored if the `recursive` option is not
5358  `true`. **Default:** `0`.
5359  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
5360  recursive mode, errors are not reported if `path` does not exist, and
5361  operations are retried on failure. **Default:** `false`.
5362  * `retryDelay` {integer} The amount of time in milliseconds to wait between
5363  retries. This option is ignored if the `recursive` option is not `true`.
5364  **Default:** `100`.
5365* Returns: {Promise}
5366
5367Removes the directory identified by `path` then resolves the `Promise` with
5368no arguments upon success.
5369
5370Using `fsPromises.rmdir()` on a file (not a directory) results in the
5371`Promise` being rejected with an `ENOENT` error on Windows and an `ENOTDIR`
5372error on POSIX.
5373
5374### `fsPromises.stat(path[, options])`
5375<!-- YAML
5376added: v10.0.0
5377changes:
5378  - version: v10.5.0
5379    pr-url: https://github.com/nodejs/node/pull/20220
5380    description: Accepts an additional `options` object to specify whether
5381                 the numeric values returned should be bigint.
5382-->
5383
5384* `path` {string|Buffer|URL}
5385* `options` {Object}
5386  * `bigint` {boolean} Whether the numeric values in the returned
5387    [`fs.Stats`][] object should be `bigint`. **Default:** `false`.
5388* Returns: {Promise}
5389
5390The `Promise` is resolved with the [`fs.Stats`][] object for the given `path`.
5391
5392### `fsPromises.symlink(target, path[, type])`
5393<!-- YAML
5394added: v10.0.0
5395-->
5396
5397* `target` {string|Buffer|URL}
5398* `path` {string|Buffer|URL}
5399* `type` {string} **Default:** `'file'`
5400* Returns: {Promise}
5401
5402Creates a symbolic link then resolves the `Promise` with no arguments upon
5403success.
5404
5405The `type` argument is only used on Windows platforms and can be one of `'dir'`,
5406`'file'`, or `'junction'`. Windows junction points require the destination path
5407to be absolute. When using `'junction'`, the `target` argument will
5408automatically be normalized to absolute path.
5409
5410### `fsPromises.truncate(path[, len])`
5411<!-- YAML
5412added: v10.0.0
5413-->
5414
5415* `path` {string|Buffer|URL}
5416* `len` {integer} **Default:** `0`
5417* Returns: {Promise}
5418
5419Truncates the `path` then resolves the `Promise` with no arguments upon
5420success. The `path` *must* be a string or `Buffer`.
5421
5422### `fsPromises.unlink(path)`
5423<!-- YAML
5424added: v10.0.0
5425-->
5426
5427* `path` {string|Buffer|URL}
5428* Returns: {Promise}
5429
5430Asynchronous unlink(2). The `Promise` is resolved with no arguments upon
5431success.
5432
5433### `fsPromises.utimes(path, atime, mtime)`
5434<!-- YAML
5435added: v10.0.0
5436-->
5437
5438* `path` {string|Buffer|URL}
5439* `atime` {number|string|Date}
5440* `mtime` {number|string|Date}
5441* Returns: {Promise}
5442
5443Change the file system timestamps of the object referenced by `path` then
5444resolves the `Promise` with no arguments upon success.
5445
5446The `atime` and `mtime` arguments follow these rules:
5447
5448* Values can be either numbers representing Unix epoch time, `Date`s, or a
5449  numeric string like `'123456789.0'`.
5450* If the value can not be converted to a number, or is `NaN`, `Infinity` or
5451  `-Infinity`, an `Error` will be thrown.
5452
5453### `fsPromises.writeFile(file, data[, options])`
5454<!-- YAML
5455added: v10.0.0
5456-->
5457
5458* `file` {string|Buffer|URL|FileHandle} filename or `FileHandle`
5459* `data` {string|Buffer|Uint8Array}
5460* `options` {Object|string}
5461  * `encoding` {string|null} **Default:** `'utf8'`
5462  * `mode` {integer} **Default:** `0o666`
5463  * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.
5464* Returns: {Promise}
5465
5466Asynchronously writes data to a file, replacing the file if it already exists.
5467`data` can be a string or a buffer. The `Promise` will be resolved with no
5468arguments upon success.
5469
5470The `encoding` option is ignored if `data` is a buffer.
5471
5472If `options` is a string, then it specifies the encoding.
5473
5474Any specified `FileHandle` has to support writing.
5475
5476It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
5477without waiting for the `Promise` to be resolved (or rejected).
5478
5479## FS constants
5480
5481The following constants are exported by `fs.constants`.
5482
5483Not every constant will be available on every operating system.
5484
5485To use more than one constant, use the bitwise OR `|` operator.
5486
5487Example:
5488
5489```js
5490const fs = require('fs');
5491
5492const {
5493  O_RDWR,
5494  O_CREAT,
5495  O_EXCL
5496} = fs.constants;
5497
5498fs.open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
5499  // ...
5500});
5501```
5502
5503### File access constants
5504
5505The following constants are meant for use with [`fs.access()`][].
5506
5507<table>
5508  <tr>
5509    <th>Constant</th>
5510    <th>Description</th>
5511  </tr>
5512  <tr>
5513    <td><code>F_OK</code></td>
5514    <td>Flag indicating that the file is visible to the calling process.
5515     This is useful for determining if a file exists, but says nothing
5516     about <code>rwx</code> permissions. Default if no mode is specified.</td>
5517  </tr>
5518  <tr>
5519    <td><code>R_OK</code></td>
5520    <td>Flag indicating that the file can be read by the calling process.</td>
5521  </tr>
5522  <tr>
5523    <td><code>W_OK</code></td>
5524    <td>Flag indicating that the file can be written by the calling
5525    process.</td>
5526  </tr>
5527  <tr>
5528    <td><code>X_OK</code></td>
5529    <td>Flag indicating that the file can be executed by the calling
5530    process. This has no effect on Windows
5531    (will behave like <code>fs.constants.F_OK</code>).</td>
5532  </tr>
5533</table>
5534
5535### File copy constants
5536
5537The following constants are meant for use with [`fs.copyFile()`][].
5538
5539<table>
5540  <tr>
5541    <th>Constant</th>
5542    <th>Description</th>
5543  </tr>
5544  <tr>
5545    <td><code>COPYFILE_EXCL</code></td>
5546    <td>If present, the copy operation will fail with an error if the
5547    destination path already exists.</td>
5548  </tr>
5549  <tr>
5550    <td><code>COPYFILE_FICLONE</code></td>
5551    <td>If present, the copy operation will attempt to create a
5552    copy-on-write reflink. If the underlying platform does not support
5553    copy-on-write, then a fallback copy mechanism is used.</td>
5554  </tr>
5555  <tr>
5556    <td><code>COPYFILE_FICLONE_FORCE</code></td>
5557    <td>If present, the copy operation will attempt to create a
5558    copy-on-write reflink. If the underlying platform does not support
5559    copy-on-write, then the operation will fail with an error.</td>
5560  </tr>
5561</table>
5562
5563### File open constants
5564
5565The following constants are meant for use with `fs.open()`.
5566
5567<table>
5568  <tr>
5569    <th>Constant</th>
5570    <th>Description</th>
5571  </tr>
5572  <tr>
5573    <td><code>O_RDONLY</code></td>
5574    <td>Flag indicating to open a file for read-only access.</td>
5575  </tr>
5576  <tr>
5577    <td><code>O_WRONLY</code></td>
5578    <td>Flag indicating to open a file for write-only access.</td>
5579  </tr>
5580  <tr>
5581    <td><code>O_RDWR</code></td>
5582    <td>Flag indicating to open a file for read-write access.</td>
5583  </tr>
5584  <tr>
5585    <td><code>O_CREAT</code></td>
5586    <td>Flag indicating to create the file if it does not already exist.</td>
5587  </tr>
5588  <tr>
5589    <td><code>O_EXCL</code></td>
5590    <td>Flag indicating that opening a file should fail if the
5591    <code>O_CREAT</code> flag is set and the file already exists.</td>
5592  </tr>
5593  <tr>
5594    <td><code>O_NOCTTY</code></td>
5595    <td>Flag indicating that if path identifies a terminal device, opening the
5596    path shall not cause that terminal to become the controlling terminal for
5597    the process (if the process does not already have one).</td>
5598  </tr>
5599  <tr>
5600    <td><code>O_TRUNC</code></td>
5601    <td>Flag indicating that if the file exists and is a regular file, and the
5602    file is opened successfully for write access, its length shall be truncated
5603    to zero.</td>
5604  </tr>
5605  <tr>
5606    <td><code>O_APPEND</code></td>
5607    <td>Flag indicating that data will be appended to the end of the file.</td>
5608  </tr>
5609  <tr>
5610    <td><code>O_DIRECTORY</code></td>
5611    <td>Flag indicating that the open should fail if the path is not a
5612    directory.</td>
5613  </tr>
5614  <tr>
5615  <td><code>O_NOATIME</code></td>
5616    <td>Flag indicating reading accesses to the file system will no longer
5617    result in an update to the <code>atime</code> information associated with
5618    the file. This flag is available on Linux operating systems only.</td>
5619  </tr>
5620  <tr>
5621    <td><code>O_NOFOLLOW</code></td>
5622    <td>Flag indicating that the open should fail if the path is a symbolic
5623    link.</td>
5624  </tr>
5625  <tr>
5626    <td><code>O_SYNC</code></td>
5627    <td>Flag indicating that the file is opened for synchronized I/O with write
5628    operations waiting for file integrity.</td>
5629  </tr>
5630  <tr>
5631    <td><code>O_DSYNC</code></td>
5632    <td>Flag indicating that the file is opened for synchronized I/O with write
5633    operations waiting for data integrity.</td>
5634  </tr>
5635  <tr>
5636    <td><code>O_SYMLINK</code></td>
5637    <td>Flag indicating to open the symbolic link itself rather than the
5638    resource it is pointing to.</td>
5639  </tr>
5640  <tr>
5641    <td><code>O_DIRECT</code></td>
5642    <td>When set, an attempt will be made to minimize caching effects of file
5643    I/O.</td>
5644  </tr>
5645  <tr>
5646    <td><code>O_NONBLOCK</code></td>
5647    <td>Flag indicating to open the file in nonblocking mode when possible.</td>
5648  </tr>
5649  <tr>
5650    <td><code>UV_FS_O_FILEMAP</code></td>
5651    <td>When set, a memory file mapping is used to access the file. This flag
5652    is available on Windows operating systems only. On other operating systems,
5653    this flag is ignored.</td>
5654  </tr>
5655</table>
5656
5657### File type constants
5658
5659The following constants are meant for use with the [`fs.Stats`][] object's
5660`mode` property for determining a file's type.
5661
5662<table>
5663  <tr>
5664    <th>Constant</th>
5665    <th>Description</th>
5666  </tr>
5667  <tr>
5668    <td><code>S_IFMT</code></td>
5669    <td>Bit mask used to extract the file type code.</td>
5670  </tr>
5671  <tr>
5672    <td><code>S_IFREG</code></td>
5673    <td>File type constant for a regular file.</td>
5674  </tr>
5675  <tr>
5676    <td><code>S_IFDIR</code></td>
5677    <td>File type constant for a directory.</td>
5678  </tr>
5679  <tr>
5680    <td><code>S_IFCHR</code></td>
5681    <td>File type constant for a character-oriented device file.</td>
5682  </tr>
5683  <tr>
5684    <td><code>S_IFBLK</code></td>
5685    <td>File type constant for a block-oriented device file.</td>
5686  </tr>
5687  <tr>
5688    <td><code>S_IFIFO</code></td>
5689    <td>File type constant for a FIFO/pipe.</td>
5690  </tr>
5691  <tr>
5692    <td><code>S_IFLNK</code></td>
5693    <td>File type constant for a symbolic link.</td>
5694  </tr>
5695  <tr>
5696    <td><code>S_IFSOCK</code></td>
5697    <td>File type constant for a socket.</td>
5698  </tr>
5699</table>
5700
5701### File mode constants
5702
5703The following constants are meant for use with the [`fs.Stats`][] object's
5704`mode` property for determining the access permissions for a file.
5705
5706<table>
5707  <tr>
5708    <th>Constant</th>
5709    <th>Description</th>
5710  </tr>
5711  <tr>
5712    <td><code>S_IRWXU</code></td>
5713    <td>File mode indicating readable, writable, and executable by owner.</td>
5714  </tr>
5715  <tr>
5716    <td><code>S_IRUSR</code></td>
5717    <td>File mode indicating readable by owner.</td>
5718  </tr>
5719  <tr>
5720    <td><code>S_IWUSR</code></td>
5721    <td>File mode indicating writable by owner.</td>
5722  </tr>
5723  <tr>
5724    <td><code>S_IXUSR</code></td>
5725    <td>File mode indicating executable by owner.</td>
5726  </tr>
5727  <tr>
5728    <td><code>S_IRWXG</code></td>
5729    <td>File mode indicating readable, writable, and executable by group.</td>
5730  </tr>
5731  <tr>
5732    <td><code>S_IRGRP</code></td>
5733    <td>File mode indicating readable by group.</td>
5734  </tr>
5735  <tr>
5736    <td><code>S_IWGRP</code></td>
5737    <td>File mode indicating writable by group.</td>
5738  </tr>
5739  <tr>
5740    <td><code>S_IXGRP</code></td>
5741    <td>File mode indicating executable by group.</td>
5742  </tr>
5743  <tr>
5744    <td><code>S_IRWXO</code></td>
5745    <td>File mode indicating readable, writable, and executable by others.</td>
5746  </tr>
5747  <tr>
5748    <td><code>S_IROTH</code></td>
5749    <td>File mode indicating readable by others.</td>
5750  </tr>
5751  <tr>
5752    <td><code>S_IWOTH</code></td>
5753    <td>File mode indicating writable by others.</td>
5754  </tr>
5755  <tr>
5756    <td><code>S_IXOTH</code></td>
5757    <td>File mode indicating executable by others.</td>
5758  </tr>
5759</table>
5760
5761## File system flags
5762
5763The following flags are available wherever the `flag` option takes a
5764string.
5765
5766* `'a'`: Open file for appending.
5767  The file is created if it does not exist.
5768
5769* `'ax'`: Like `'a'` but fails if the path exists.
5770
5771* `'a+'`: Open file for reading and appending.
5772  The file is created if it does not exist.
5773
5774* `'ax+'`: Like `'a+'` but fails if the path exists.
5775
5776* `'as'`: Open file for appending in synchronous mode.
5777  The file is created if it does not exist.
5778
5779* `'as+'`: Open file for reading and appending in synchronous mode.
5780  The file is created if it does not exist.
5781
5782* `'r'`: Open file for reading.
5783  An exception occurs if the file does not exist.
5784
5785* `'r+'`: Open file for reading and writing.
5786  An exception occurs if the file does not exist.
5787
5788* `'rs+'`: Open file for reading and writing in synchronous mode. Instructs
5789  the operating system to bypass the local file system cache.
5790
5791  This is primarily useful for opening files on NFS mounts as it allows
5792  skipping the potentially stale local cache. It has a very real impact on
5793  I/O performance so using this flag is not recommended unless it is needed.
5794
5795  This doesn't turn `fs.open()` or `fsPromises.open()` into a synchronous
5796  blocking call. If synchronous operation is desired, something like
5797  `fs.openSync()` should be used.
5798
5799* `'w'`: Open file for writing.
5800  The file is created (if it does not exist) or truncated (if it exists).
5801
5802* `'wx'`: Like `'w'` but fails if the path exists.
5803
5804* `'w+'`: Open file for reading and writing.
5805The file is created (if it does not exist) or truncated (if it exists).
5806
5807* `'wx+'`: Like `'w+'` but fails if the path exists.
5808
5809`flag` can also be a number as documented by open(2); commonly used constants
5810are available from `fs.constants`. On Windows, flags are translated to
5811their equivalent ones where applicable, e.g. `O_WRONLY` to `FILE_GENERIC_WRITE`,
5812or `O_EXCL|O_CREAT` to `CREATE_NEW`, as accepted by `CreateFileW`.
5813
5814The exclusive flag `'x'` (`O_EXCL` flag in open(2)) causes the operation to
5815return an error if the path already exists. On POSIX, if the path is a symbolic
5816link, using `O_EXCL` returns an error even if the link is to a path that does
5817not exist. The exclusive flag may or may not work with network file systems.
5818
5819On Linux, positional writes don't work when the file is opened in append mode.
5820The kernel ignores the position argument and always appends the data to
5821the end of the file.
5822
5823Modifying a file rather than replacing it may require a flags mode of `'r+'`
5824rather than the default mode `'w'`.
5825
5826The behavior of some flags are platform-specific. As such, opening a directory
5827on macOS and Linux with the `'a+'` flag, as in the example below, will return an
5828error. In contrast, on Windows and FreeBSD, a file descriptor or a `FileHandle`
5829will be returned.
5830
5831```js
5832// macOS and Linux
5833fs.open('<directory>', 'a+', (err, fd) => {
5834  // => [Error: EISDIR: illegal operation on a directory, open <directory>]
5835});
5836
5837// Windows and FreeBSD
5838fs.open('<directory>', 'a+', (err, fd) => {
5839  // => null, <fd>
5840});
5841```
5842
5843On Windows, opening an existing hidden file using the `'w'` flag (either
5844through `fs.open()` or `fs.writeFile()` or `fsPromises.open()`) will fail with
5845`EPERM`. Existing hidden files can be opened for writing with the `'r+'` flag.
5846
5847A call to `fs.ftruncate()` or `filehandle.truncate()` can be used to reset
5848the file contents.
5849
5850[`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/
5851[`Buffer.byteLength`]: buffer.html#buffer_static_method_buffer_bytelength_string_encoding
5852[`Buffer`]: buffer.html#buffer_buffer
5853[`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
5854[`Number.MAX_SAFE_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
5855[`ReadDirectoryChangesW`]: https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw
5856[`ReadStream`]: #fs_class_fs_readstream
5857[Readable Stream]: stream.html#stream_class_stream_readable
5858[`URL`]: url.html#url_the_whatwg_url_api
5859[`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size
5860[`WriteStream`]: #fs_class_fs_writestream
5861[`event ports`]: https://illumos.org/man/port_create
5862[`filehandle.writeFile()`]: #fs_filehandle_writefile_data_options
5863[`fs.Dir`]: #fs_class_fs_dir
5864[`fs.Dirent`]: #fs_class_fs_dirent
5865[`fs.FSWatcher`]: #fs_class_fs_fswatcher
5866[`fs.Stats`]: #fs_class_fs_stats
5867[`fs.access()`]: #fs_fs_access_path_mode_callback
5868[`fs.chmod()`]: #fs_fs_chmod_path_mode_callback
5869[`fs.chown()`]: #fs_fs_chown_path_uid_gid_callback
5870[`fs.copyFile()`]: #fs_fs_copyfile_src_dest_flags_callback
5871[`fs.createReadStream()`]: #fs_fs_createreadstream_path_options
5872[`fs.createWriteStream()`]: #fs_fs_createwritestream_path_options
5873[`fs.exists()`]: fs.html#fs_fs_exists_path_callback
5874[`fs.fstat()`]: #fs_fs_fstat_fd_options_callback
5875[`fs.ftruncate()`]: #fs_fs_ftruncate_fd_len_callback
5876[`fs.futimes()`]: #fs_fs_futimes_fd_atime_mtime_callback
5877[`fs.lstat()`]: #fs_fs_lstat_path_options_callback
5878[`fs.lutimes()`]: #fs_fs_lutimes_path_atime_mtime_callback
5879[`fs.mkdir()`]: #fs_fs_mkdir_path_options_callback
5880[`fs.mkdtemp()`]: #fs_fs_mkdtemp_prefix_options_callback
5881[`fs.open()`]: #fs_fs_open_path_flags_mode_callback
5882[`fs.opendir()`]: #fs_fs_opendir_path_options_callback
5883[`fs.opendirSync()`]: #fs_fs_opendirsync_path_options
5884[`fs.read()`]: #fs_fs_read_fd_buffer_offset_length_position_callback
5885[`fs.readFile()`]: #fs_fs_readfile_path_options_callback
5886[`fs.readFileSync()`]: #fs_fs_readfilesync_path_options
5887[`fs.readdir()`]: #fs_fs_readdir_path_options_callback
5888[`fs.readdirSync()`]: #fs_fs_readdirsync_path_options
5889[`fs.readv()`]: #fs_fs_readv_fd_buffers_position_callback
5890[`fs.realpath()`]: #fs_fs_realpath_path_options_callback
5891[`fs.rmdir()`]: #fs_fs_rmdir_path_options_callback
5892[`fs.stat()`]: #fs_fs_stat_path_options_callback
5893[`fs.symlink()`]: #fs_fs_symlink_target_path_type_callback
5894[`fs.utimes()`]: #fs_fs_utimes_path_atime_mtime_callback
5895[`fs.watch()`]: #fs_fs_watch_filename_options_listener
5896[`fs.write(fd, buffer...)`]: #fs_fs_write_fd_buffer_offset_length_position_callback
5897[`fs.write(fd, string...)`]: #fs_fs_write_fd_string_position_encoding_callback
5898[`fs.writeFile()`]: #fs_fs_writefile_file_data_options_callback
5899[`fs.writev()`]: #fs_fs_writev_fd_buffers_position_callback
5900[`fsPromises.open()`]: #fs_fspromises_open_path_flags_mode
5901[`fsPromises.opendir()`]: #fs_fspromises_opendir_path_options
5902[`fsPromises.utimes()`]: #fs_fspromises_utimes_path_atime_mtime
5903[`inotify(7)`]: https://man7.org/linux/man-pages/man7/inotify.7.html
5904[`kqueue(2)`]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
5905[`net.Socket`]: net.html#net_class_net_socket
5906[`stat()`]: fs.html#fs_fs_stat_path_options_callback
5907[`util.promisify()`]: util.html#util_util_promisify_original
5908[Caveats]: #fs_caveats
5909[Common System Errors]: errors.html#errors_common_system_errors
5910[FS constants]: #fs_fs_constants_1
5911[File access constants]: #fs_file_access_constants
5912[MDN-Date]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
5913[MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
5914[MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
5915[MSDN-Using-Streams]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams
5916[Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file
5917[bigints]: https://tc39.github.io/proposal-bigint
5918[chcp]: https://ss64.com/nt/chcp.html
5919[inode]: https://en.wikipedia.org/wiki/Inode
5920[support of file system `flags`]: #fs_file_system_flags
5921[Writable Stream]: #stream_class_stream_writable
5922