xref: /third_party/node/doc/api/fs.md (revision 1cb0ef41)
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 `node:fs` module enables interacting with the file system in a
12way modeled on standard POSIX functions.
13
14To use the promise-based APIs:
15
16```mjs
17import * as fs from 'node:fs/promises';
18```
19
20```cjs
21const fs = require('node:fs/promises');
22```
23
24To use the callback and sync APIs:
25
26```mjs
27import * as fs from 'node:fs';
28```
29
30```cjs
31const fs = require('node:fs');
32```
33
34All file system operations have synchronous, callback, and promise-based
35forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
36
37## Promise example
38
39Promise-based operations return a promise that is fulfilled when the
40asynchronous operation is complete.
41
42```mjs
43import { unlink } from 'node:fs/promises';
44
45try {
46  await unlink('/tmp/hello');
47  console.log('successfully deleted /tmp/hello');
48} catch (error) {
49  console.error('there was an error:', error.message);
50}
51```
52
53```cjs
54const { unlink } = require('node:fs/promises');
55
56(async function(path) {
57  try {
58    await unlink(path);
59    console.log(`successfully deleted ${path}`);
60  } catch (error) {
61    console.error('there was an error:', error.message);
62  }
63})('/tmp/hello');
64```
65
66## Callback example
67
68The callback form takes a completion callback function as its last
69argument and invokes the operation asynchronously. The arguments passed to
70the completion callback depend on the method, but the first argument is always
71reserved for an exception. If the operation is completed successfully, then
72the first argument is `null` or `undefined`.
73
74```mjs
75import { unlink } from 'node:fs';
76
77unlink('/tmp/hello', (err) => {
78  if (err) throw err;
79  console.log('successfully deleted /tmp/hello');
80});
81```
82
83```cjs
84const { unlink } = require('node:fs');
85
86unlink('/tmp/hello', (err) => {
87  if (err) throw err;
88  console.log('successfully deleted /tmp/hello');
89});
90```
91
92The callback-based versions of the `node:fs` module APIs are preferable over
93the use of the promise APIs when maximal performance (both in terms of
94execution time and memory allocation) is required.
95
96## Synchronous example
97
98The synchronous APIs block the Node.js event loop and further JavaScript
99execution until the operation is complete. Exceptions are thrown immediately
100and can be handled using `try…catch`, or can be allowed to bubble up.
101
102```mjs
103import { unlinkSync } from 'node:fs';
104
105try {
106  unlinkSync('/tmp/hello');
107  console.log('successfully deleted /tmp/hello');
108} catch (err) {
109  // handle the error
110}
111```
112
113```cjs
114const { unlinkSync } = require('node:fs');
115
116try {
117  unlinkSync('/tmp/hello');
118  console.log('successfully deleted /tmp/hello');
119} catch (err) {
120  // handle the error
121}
122```
123
124## Promises API
125
126<!-- YAML
127added: v10.0.0
128changes:
129  - version: v14.0.0
130    pr-url: https://github.com/nodejs/node/pull/31553
131    description: Exposed as `require('fs/promises')`.
132  - version:
133    - v11.14.0
134    - v10.17.0
135    pr-url: https://github.com/nodejs/node/pull/26581
136    description: This API is no longer experimental.
137  - version: v10.1.0
138    pr-url: https://github.com/nodejs/node/pull/20504
139    description: The API is accessible via `require('fs').promises` only.
140-->
141
142The `fs/promises` API provides asynchronous file system methods that return
143promises.
144
145The promise APIs use the underlying Node.js threadpool to perform file
146system operations off the event loop thread. These operations are not
147synchronized or threadsafe. Care must be taken when performing multiple
148concurrent modifications on the same file or data corruption may occur.
149
150### Class: `FileHandle`
151
152<!-- YAML
153added: v10.0.0
154-->
155
156A {FileHandle} object is an object wrapper for a numeric file descriptor.
157
158Instances of the {FileHandle} object are created by the `fsPromises.open()`
159method.
160
161All {FileHandle} objects are {EventEmitter}s.
162
163If a {FileHandle} is not closed using the `filehandle.close()` method, it will
164try to automatically close the file descriptor and emit a process warning,
165helping to prevent memory leaks. Please do not rely on this behavior because
166it can be unreliable and the file may not be closed. Instead, always explicitly
167close {FileHandle}s. Node.js may change this behavior in the future.
168
169#### Event: `'close'`
170
171<!-- YAML
172added: v15.4.0
173-->
174
175The `'close'` event is emitted when the {FileHandle} has been closed and can no
176longer be used.
177
178#### `filehandle.appendFile(data[, options])`
179
180<!-- YAML
181added: v10.0.0
182changes:
183  - version:
184      - v15.14.0
185      - v14.18.0
186    pr-url: https://github.com/nodejs/node/pull/37490
187    description: The `data` argument supports `AsyncIterable`, `Iterable`, and `Stream`.
188  - version: v14.0.0
189    pr-url: https://github.com/nodejs/node/pull/31030
190    description: The `data` parameter won't coerce unsupported input to
191                 strings anymore.
192-->
193
194* `data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream}
195* `options` {Object|string}
196  * `encoding` {string|null} **Default:** `'utf8'`
197* Returns: {Promise} Fulfills with `undefined` upon success.
198
199Alias of [`filehandle.writeFile()`][].
200
201When operating on file handles, the mode cannot be changed from what it was set
202to with [`fsPromises.open()`][]. Therefore, this is equivalent to
203[`filehandle.writeFile()`][].
204
205#### `filehandle.chmod(mode)`
206
207<!-- YAML
208added: v10.0.0
209-->
210
211* `mode` {integer} the file mode bit mask.
212* Returns: {Promise} Fulfills with `undefined` upon success.
213
214Modifies the permissions on the file. See chmod(2).
215
216#### `filehandle.chown(uid, gid)`
217
218<!-- YAML
219added: v10.0.0
220-->
221
222* `uid` {integer} The file's new owner's user id.
223* `gid` {integer} The file's new group's group id.
224* Returns: {Promise} Fulfills with `undefined` upon success.
225
226Changes the ownership of the file. A wrapper for chown(2).
227
228#### `filehandle.close()`
229
230<!-- YAML
231added: v10.0.0
232-->
233
234* Returns: {Promise} Fulfills with `undefined` upon success.
235
236Closes the file handle after waiting for any pending operation on the handle to
237complete.
238
239```mjs
240import { open } from 'node:fs/promises';
241
242let filehandle;
243try {
244  filehandle = await open('thefile.txt', 'r');
245} finally {
246  await filehandle?.close();
247}
248```
249
250#### `filehandle.createReadStream([options])`
251
252<!-- YAML
253added: v16.11.0
254-->
255
256* `options` {Object}
257  * `encoding` {string} **Default:** `null`
258  * `autoClose` {boolean} **Default:** `true`
259  * `emitClose` {boolean} **Default:** `true`
260  * `start` {integer}
261  * `end` {integer} **Default:** `Infinity`
262  * `highWaterMark` {integer} **Default:** `64 * 1024`
263* Returns: {fs.ReadStream}
264
265Unlike the 16 KiB default `highWaterMark` for a {stream.Readable}, the stream
266returned by this method has a default `highWaterMark` of 64 KiB.
267
268`options` can include `start` and `end` values to read a range of bytes from
269the file instead of the entire file. Both `start` and `end` are inclusive and
270start counting at 0, allowed values are in the
271\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is
272omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from
273the current file position. The `encoding` can be any one of those accepted by
274{Buffer}.
275
276If the `FileHandle` points to a character device that only supports blocking
277reads (such as keyboard or sound card), read operations do not finish until data
278is available. This can prevent the process from exiting and the stream from
279closing naturally.
280
281By default, the stream will emit a `'close'` event after it has been
282destroyed.  Set the `emitClose` option to `false` to change this behavior.
283
284```mjs
285import { open } from 'node:fs/promises';
286
287const fd = await open('/dev/input/event0');
288// Create a stream from some character device.
289const stream = fd.createReadStream();
290setTimeout(() => {
291  stream.close(); // This may not close the stream.
292  // Artificially marking end-of-stream, as if the underlying resource had
293  // indicated end-of-file by itself, allows the stream to close.
294  // This does not cancel pending read operations, and if there is such an
295  // operation, the process may still not be able to exit successfully
296  // until it finishes.
297  stream.push(null);
298  stream.read(0);
299}, 100);
300```
301
302If `autoClose` is false, then the file descriptor won't be closed, even if
303there's an error. It is the application's responsibility to close it and make
304sure there's no file descriptor leak. If `autoClose` is set to true (default
305behavior), on `'error'` or `'end'` the file descriptor will be closed
306automatically.
307
308An example to read the last 10 bytes of a file which is 100 bytes long:
309
310```mjs
311import { open } from 'node:fs/promises';
312
313const fd = await open('sample.txt');
314fd.createReadStream({ start: 90, end: 99 });
315```
316
317#### `filehandle.createWriteStream([options])`
318
319<!-- YAML
320added: v16.11.0
321-->
322
323* `options` {Object}
324  * `encoding` {string} **Default:** `'utf8'`
325  * `autoClose` {boolean} **Default:** `true`
326  * `emitClose` {boolean} **Default:** `true`
327  * `start` {integer}
328* Returns: {fs.WriteStream}
329
330`options` may also include a `start` option to allow writing data at some
331position past the beginning of the file, allowed values are in the
332\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than
333replacing it may require the `flags` `open` option to be set to `r+` rather than
334the default `r`. The `encoding` can be any one of those accepted by {Buffer}.
335
336If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
337the file descriptor will be closed automatically. If `autoClose` is false,
338then the file descriptor won't be closed, even if there's an error.
339It is the application's responsibility to close it and make sure there's no
340file descriptor leak.
341
342By default, the stream will emit a `'close'` event after it has been
343destroyed.  Set the `emitClose` option to `false` to change this behavior.
344
345#### `filehandle.datasync()`
346
347<!-- YAML
348added: v10.0.0
349-->
350
351* Returns: {Promise} Fulfills with `undefined` upon success.
352
353Forces all currently queued I/O operations associated with the file to the
354operating system's synchronized I/O completion state. Refer to the POSIX
355fdatasync(2) documentation for details.
356
357Unlike `filehandle.sync` this method does not flush modified metadata.
358
359#### `filehandle.fd`
360
361<!-- YAML
362added: v10.0.0
363-->
364
365* {number} The numeric file descriptor managed by the {FileHandle} object.
366
367#### `filehandle.read(buffer, offset, length, position)`
368
369<!-- YAML
370added: v10.0.0
371-->
372
373* `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the
374  file data read.
375* `offset` {integer} The location in the buffer at which to start filling.
376* `length` {integer} The number of bytes to read.
377* `position` {integer|null} The location where to begin reading data from the
378  file. If `null`, data will be read from the current file position, and
379  the position will be updated. If `position` is an integer, the current
380  file position will remain unchanged.
381* Returns: {Promise} Fulfills upon success with an object with two properties:
382  * `bytesRead` {integer} The number of bytes read
383  * `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer`
384    argument.
385
386Reads data from the file and stores that in the given buffer.
387
388If the file is not modified concurrently, the end-of-file is reached when the
389number of bytes read is zero.
390
391#### `filehandle.read([options])`
392
393<!-- YAML
394added:
395 - v13.11.0
396 - v12.17.0
397-->
398
399* `options` {Object}
400  * `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the
401    file data read. **Default:** `Buffer.alloc(16384)`
402  * `offset` {integer} The location in the buffer at which to start filling.
403    **Default:** `0`
404  * `length` {integer} The number of bytes to read. **Default:**
405    `buffer.byteLength - offset`
406  * `position` {integer|null} The location where to begin reading data from the
407    file. If `null`, data will be read from the current file position, and
408    the position will be updated. If `position` is an integer, the current
409    file position will remain unchanged. **Default:**: `null`
410* Returns: {Promise} Fulfills upon success with an object with two properties:
411  * `bytesRead` {integer} The number of bytes read
412  * `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer`
413    argument.
414
415Reads data from the file and stores that in the given buffer.
416
417If the file is not modified concurrently, the end-of-file is reached when the
418number of bytes read is zero.
419
420#### `filehandle.read(buffer[, options])`
421
422<!-- YAML
423added: v18.2.0
424-->
425
426* `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the
427  file data read.
428* `options` {Object}
429  * `offset` {integer} The location in the buffer at which to start filling.
430    **Default:** `0`
431  * `length` {integer} The number of bytes to read. **Default:**
432    `buffer.byteLength - offset`
433  * `position` {integer} The location where to begin reading data from the
434    file. If `null`, data will be read from the current file position, and
435    the position will be updated. If `position` is an integer, the current
436    file position will remain unchanged. **Default:**: `null`
437* Returns: {Promise} Fulfills upon success with an object with two properties:
438  * `bytesRead` {integer} The number of bytes read
439  * `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer`
440    argument.
441
442Reads data from the file and stores that in the given buffer.
443
444If the file is not modified concurrently, the end-of-file is reached when the
445number of bytes read is zero.
446
447#### `filehandle.readableWebStream([options])`
448
449<!-- YAML
450added: v17.0.0
451changes:
452  - version: v18.17.0
453    pr-url: https://github.com/nodejs/node/pull/46933
454    description: Added option to create a 'bytes' stream.
455-->
456
457> Stability: 1 - Experimental
458
459* `options` {Object}
460  * `type` {string|undefined} Whether to open a normal or a `'bytes'` stream.
461    **Default:** `undefined`
462
463* Returns: {ReadableStream}
464
465Returns a `ReadableStream` that may be used to read the files data.
466
467An error will be thrown if this method is called more than once or is called
468after the `FileHandle` is closed or closing.
469
470```mjs
471import {
472  open,
473} from 'node:fs/promises';
474
475const file = await open('./some/file/to/read');
476
477for await (const chunk of file.readableWebStream())
478  console.log(chunk);
479
480await file.close();
481```
482
483```cjs
484const {
485  open,
486} = require('node:fs/promises');
487
488(async () => {
489  const file = await open('./some/file/to/read');
490
491  for await (const chunk of file.readableWebStream())
492    console.log(chunk);
493
494  await file.close();
495})();
496```
497
498While the `ReadableStream` will read the file to completion, it will not
499close the `FileHandle` automatically. User code must still call the
500`fileHandle.close()` method.
501
502#### `filehandle.readFile(options)`
503
504<!-- YAML
505added: v10.0.0
506-->
507
508* `options` {Object|string}
509  * `encoding` {string|null} **Default:** `null`
510  * `signal` {AbortSignal} allows aborting an in-progress readFile
511* Returns: {Promise} Fulfills upon a successful read with the contents of the
512  file. If no encoding is specified (using `options.encoding`), the data is
513  returned as a {Buffer} object. Otherwise, the data will be a string.
514
515Asynchronously reads the entire contents of a file.
516
517If `options` is a string, then it specifies the `encoding`.
518
519The {FileHandle} has to support reading.
520
521If one or more `filehandle.read()` calls are made on a file handle and then a
522`filehandle.readFile()` call is made, the data will be read from the current
523position till the end of the file. It doesn't always read from the beginning
524of the file.
525
526#### `filehandle.readLines([options])`
527
528<!-- YAML
529added: v18.11.0
530-->
531
532* `options` {Object}
533  * `encoding` {string} **Default:** `null`
534  * `autoClose` {boolean} **Default:** `true`
535  * `emitClose` {boolean} **Default:** `true`
536  * `start` {integer}
537  * `end` {integer} **Default:** `Infinity`
538  * `highWaterMark` {integer} **Default:** `64 * 1024`
539* Returns: {readline.InterfaceConstructor}
540
541Convenience method to create a `readline` interface and stream over the file.
542See [`filehandle.createReadStream()`][] for the options.
543
544```mjs
545import { open } from 'node:fs/promises';
546
547const file = await open('./some/file/to/read');
548
549for await (const line of file.readLines()) {
550  console.log(line);
551}
552```
553
554```cjs
555const { open } = require('node:fs/promises');
556
557(async () => {
558  const file = await open('./some/file/to/read');
559
560  for await (const line of file.readLines()) {
561    console.log(line);
562  }
563})();
564```
565
566#### `filehandle.readv(buffers[, position])`
567
568<!-- YAML
569added:
570 - v13.13.0
571 - v12.17.0
572-->
573
574* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]}
575* `position` {integer|null} The offset from the beginning of the file where
576  the data should be read from. If `position` is not a `number`, the data will
577  be read from the current position. **Default:** `null`
578* Returns: {Promise} Fulfills upon success an object containing two properties:
579  * `bytesRead` {integer} the number of bytes read
580  * `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} property containing
581    a reference to the `buffers` input.
582
583Read from a file and write to an array of {ArrayBufferView}s
584
585#### `filehandle.stat([options])`
586
587<!-- YAML
588added: v10.0.0
589changes:
590  - version: v10.5.0
591    pr-url: https://github.com/nodejs/node/pull/20220
592    description: Accepts an additional `options` object to specify whether
593                 the numeric values returned should be bigint.
594-->
595
596* `options` {Object}
597  * `bigint` {boolean} Whether the numeric values in the returned
598    {fs.Stats} object should be `bigint`. **Default:** `false`.
599* Returns: {Promise} Fulfills with an {fs.Stats} for the file.
600
601#### `filehandle.sync()`
602
603<!-- YAML
604added: v10.0.0
605-->
606
607* Returns: {Promise} Fulfills with `undefined` upon success.
608
609Request that all data for the open file descriptor is flushed to the storage
610device. The specific implementation is operating system and device specific.
611Refer to the POSIX fsync(2) documentation for more detail.
612
613#### `filehandle.truncate(len)`
614
615<!-- YAML
616added: v10.0.0
617-->
618
619* `len` {integer} **Default:** `0`
620* Returns: {Promise} Fulfills with `undefined` upon success.
621
622Truncates the file.
623
624If the file was larger than `len` bytes, only the first `len` bytes will be
625retained in the file.
626
627The following example retains only the first four bytes of the file:
628
629```mjs
630import { open } from 'node:fs/promises';
631
632let filehandle = null;
633try {
634  filehandle = await open('temp.txt', 'r+');
635  await filehandle.truncate(4);
636} finally {
637  await filehandle?.close();
638}
639```
640
641If the file previously was shorter than `len` bytes, it is extended, and the
642extended part is filled with null bytes (`'\0'`):
643
644If `len` is negative then `0` will be used.
645
646#### `filehandle.utimes(atime, mtime)`
647
648<!-- YAML
649added: v10.0.0
650-->
651
652* `atime` {number|string|Date}
653* `mtime` {number|string|Date}
654* Returns: {Promise}
655
656Change the file system timestamps of the object referenced by the {FileHandle}
657then resolves the promise with no arguments upon success.
658
659#### `filehandle.write(buffer, offset[, length[, position]])`
660
661<!-- YAML
662added: v10.0.0
663changes:
664  - version: v14.0.0
665    pr-url: https://github.com/nodejs/node/pull/31030
666    description: The `buffer` parameter won't coerce unsupported input to
667                 buffers anymore.
668-->
669
670* `buffer` {Buffer|TypedArray|DataView}
671* `offset` {integer} The start position from within `buffer` where the data
672  to write begins.
673* `length` {integer} The number of bytes from `buffer` to write. **Default:**
674  `buffer.byteLength - offset`
675* `position` {integer|null} The offset from the beginning of the file where the
676  data from `buffer` should be written. If `position` is not a `number`,
677  the data will be written at the current position. See the POSIX pwrite(2)
678  documentation for more detail. **Default:** `null`
679* Returns: {Promise}
680
681Write `buffer` to the file.
682
683The promise is resolved with an object containing two properties:
684
685* `bytesWritten` {integer} the number of bytes written
686* `buffer` {Buffer|TypedArray|DataView} a reference to the
687  `buffer` written.
688
689It is unsafe to use `filehandle.write()` multiple times on the same file
690without waiting for the promise to be resolved (or rejected). For this
691scenario, use [`filehandle.createWriteStream()`][].
692
693On Linux, positional writes do not work when the file is opened in append mode.
694The kernel ignores the position argument and always appends the data to
695the end of the file.
696
697#### `filehandle.write(buffer[, options])`
698
699<!-- YAML
700added: v18.3.0
701-->
702
703* `buffer` {Buffer|TypedArray|DataView}
704* `options` {Object}
705  * `offset` {integer} **Default:** `0`
706  * `length` {integer} **Default:** `buffer.byteLength - offset`
707  * `position` {integer} **Default:** `null`
708* Returns: {Promise}
709
710Write `buffer` to the file.
711
712Similar to the above `filehandle.write` function, this version takes an
713optional `options` object. If no `options` object is specified, it will
714default with the above values.
715
716#### `filehandle.write(string[, position[, encoding]])`
717
718<!-- YAML
719added: v10.0.0
720changes:
721  - version: v14.0.0
722    pr-url: https://github.com/nodejs/node/pull/31030
723    description: The `string` parameter won't coerce unsupported input to
724                 strings anymore.
725-->
726
727* `string` {string}
728* `position` {integer|null} The offset from the beginning of the file where the
729  data from `string` should be written. If `position` is not a `number` the
730  data will be written at the current position. See the POSIX pwrite(2)
731  documentation for more detail. **Default:** `null`
732* `encoding` {string} The expected string encoding. **Default:** `'utf8'`
733* Returns: {Promise}
734
735Write `string` to the file. If `string` is not a string, the promise is
736rejected with an error.
737
738The promise is resolved with an object containing two properties:
739
740* `bytesWritten` {integer} the number of bytes written
741* `buffer` {string} a reference to the `string` written.
742
743It is unsafe to use `filehandle.write()` multiple times on the same file
744without waiting for the promise to be resolved (or rejected). For this
745scenario, use [`filehandle.createWriteStream()`][].
746
747On Linux, positional writes do not work when the file is opened in append mode.
748The kernel ignores the position argument and always appends the data to
749the end of the file.
750
751#### `filehandle.writeFile(data, options)`
752
753<!-- YAML
754added: v10.0.0
755changes:
756  - version:
757      - v15.14.0
758      - v14.18.0
759    pr-url: https://github.com/nodejs/node/pull/37490
760    description: The `data` argument supports `AsyncIterable`, `Iterable`, and `Stream`.
761  - version: v14.0.0
762    pr-url: https://github.com/nodejs/node/pull/31030
763    description: The `data` parameter won't coerce unsupported input to
764                 strings anymore.
765-->
766
767* `data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream}
768* `options` {Object|string}
769  * `encoding` {string|null} The expected character encoding when `data` is a
770    string. **Default:** `'utf8'`
771* Returns: {Promise}
772
773Asynchronously writes data to a file, replacing the file if it already exists.
774`data` can be a string, a buffer, an {AsyncIterable}, or an {Iterable} object.
775The promise is resolved with no arguments upon success.
776
777If `options` is a string, then it specifies the `encoding`.
778
779The {FileHandle} has to support writing.
780
781It is unsafe to use `filehandle.writeFile()` multiple times on the same file
782without waiting for the promise to be resolved (or rejected).
783
784If one or more `filehandle.write()` calls are made on a file handle and then a
785`filehandle.writeFile()` call is made, the data will be written from the
786current position till the end of the file. It doesn't always write from the
787beginning of the file.
788
789#### `filehandle.writev(buffers[, position])`
790
791<!-- YAML
792added: v12.9.0
793-->
794
795* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]}
796* `position` {integer|null} The offset from the beginning of the file where the
797  data from `buffers` should be written. If `position` is not a `number`,
798  the data will be written at the current position. **Default:** `null`
799* Returns: {Promise}
800
801Write an array of {ArrayBufferView}s to the file.
802
803The promise is resolved with an object containing a two properties:
804
805* `bytesWritten` {integer} the number of bytes written
806* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} a reference to the `buffers`
807  input.
808
809It is unsafe to call `writev()` multiple times on the same file without waiting
810for the promise to be resolved (or rejected).
811
812On Linux, positional writes don't work when the file is opened in append mode.
813The kernel ignores the position argument and always appends the data to
814the end of the file.
815
816#### `filehandle[Symbol.asyncDispose]()`
817
818<!-- YAML
819added: v18.18.0
820-->
821
822> Stability: 1 - Experimental
823
824An alias for `filehandle.close()`.
825
826### `fsPromises.access(path[, mode])`
827
828<!-- YAML
829added: v10.0.0
830-->
831
832* `path` {string|Buffer|URL}
833* `mode` {integer} **Default:** `fs.constants.F_OK`
834* Returns: {Promise} Fulfills with `undefined` upon success.
835
836Tests a user's permissions for the file or directory specified by `path`.
837The `mode` argument is an optional integer that specifies the accessibility
838checks to be performed. `mode` should be either the value `fs.constants.F_OK`
839or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,
840`fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.
841`fs.constants.W_OK | fs.constants.R_OK`). Check [File access constants][] for
842possible values of `mode`.
843
844If the accessibility check is successful, the promise is resolved with no
845value. If any of the accessibility checks fail, the promise is rejected
846with an {Error} object. The following example checks if the file
847`/etc/passwd` can be read and written by the current process.
848
849```mjs
850import { access, constants } from 'node:fs/promises';
851
852try {
853  await access('/etc/passwd', constants.R_OK | constants.W_OK);
854  console.log('can access');
855} catch {
856  console.error('cannot access');
857}
858```
859
860Using `fsPromises.access()` to check for the accessibility of a file before
861calling `fsPromises.open()` is not recommended. Doing so introduces a race
862condition, since other processes may change the file's state between the two
863calls. Instead, user code should open/read/write the file directly and handle
864the error raised if the file is not accessible.
865
866### `fsPromises.appendFile(path, data[, options])`
867
868<!-- YAML
869added: v10.0.0
870-->
871
872* `path` {string|Buffer|URL|FileHandle} filename or {FileHandle}
873* `data` {string|Buffer}
874* `options` {Object|string}
875  * `encoding` {string|null} **Default:** `'utf8'`
876  * `mode` {integer} **Default:** `0o666`
877  * `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
878* Returns: {Promise} Fulfills with `undefined` upon success.
879
880Asynchronously append data to a file, creating the file if it does not yet
881exist. `data` can be a string or a {Buffer}.
882
883If `options` is a string, then it specifies the `encoding`.
884
885The `mode` option only affects the newly created file. See [`fs.open()`][]
886for more details.
887
888The `path` may be specified as a {FileHandle} that has been opened
889for appending (using `fsPromises.open()`).
890
891### `fsPromises.chmod(path, mode)`
892
893<!-- YAML
894added: v10.0.0
895-->
896
897* `path` {string|Buffer|URL}
898* `mode` {string|integer}
899* Returns: {Promise} Fulfills with `undefined` upon success.
900
901Changes the permissions of a file.
902
903### `fsPromises.chown(path, uid, gid)`
904
905<!-- YAML
906added: v10.0.0
907-->
908
909* `path` {string|Buffer|URL}
910* `uid` {integer}
911* `gid` {integer}
912* Returns: {Promise} Fulfills with `undefined` upon success.
913
914Changes the ownership of a file.
915
916### `fsPromises.copyFile(src, dest[, mode])`
917
918<!-- YAML
919added: v10.0.0
920changes:
921  - version: v14.0.0
922    pr-url: https://github.com/nodejs/node/pull/27044
923    description: Changed `flags` argument to `mode` and imposed
924                 stricter type validation.
925-->
926
927* `src` {string|Buffer|URL} source filename to copy
928* `dest` {string|Buffer|URL} destination filename of the copy operation
929* `mode` {integer} Optional modifiers that specify the behavior of the copy
930  operation. It is possible to create a mask consisting of the bitwise OR of
931  two or more values (e.g.
932  `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`)
933  **Default:** `0`.
934  * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest`
935    already exists.
936  * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create
937    a copy-on-write reflink. If the platform does not support copy-on-write,
938    then a fallback copy mechanism is used.
939  * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
940    create a copy-on-write reflink. If the platform does not support
941    copy-on-write, then the operation will fail.
942* Returns: {Promise} Fulfills with `undefined` upon success.
943
944Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
945already exists.
946
947No guarantees are made about the atomicity of the copy operation. If an
948error occurs after the destination file has been opened for writing, an attempt
949will be made to remove the destination.
950
951```mjs
952import { copyFile, constants } from 'node:fs/promises';
953
954try {
955  await copyFile('source.txt', 'destination.txt');
956  console.log('source.txt was copied to destination.txt');
957} catch {
958  console.error('The file could not be copied');
959}
960
961// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
962try {
963  await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
964  console.log('source.txt was copied to destination.txt');
965} catch {
966  console.error('The file could not be copied');
967}
968```
969
970### `fsPromises.cp(src, dest[, options])`
971
972<!-- YAML
973added: v16.7.0
974changes:
975  - version: v18.17.0
976    pr-url: https://github.com/nodejs/node/pull/47084
977    description: Accept an additional `mode` option to specify
978                 the copy behavior as the `mode` argument of `fs.copyFile()`.
979  - version: v17.6.0
980    pr-url: https://github.com/nodejs/node/pull/41819
981    description: Accepts an additional `verbatimSymlinks` option to specify
982                 whether to perform path resolution for symlinks.
983-->
984
985> Stability: 1 - Experimental
986
987* `src` {string|URL} source path to copy.
988* `dest` {string|URL} destination path to copy to.
989* `options` {Object}
990  * `dereference` {boolean} dereference symlinks. **Default:** `false`.
991  * `errorOnExist` {boolean} when `force` is `false`, and the destination
992    exists, throw an error. **Default:** `false`.
993  * `filter` {Function} Function to filter copied files/directories. Return
994    `true` to copy the item, `false` to ignore it. When ignoring a directory,
995    all of its contents will be skipped as well. Can also return a `Promise`
996    that resolves to `true` or `false` **Default:** `undefined`.
997    * `src` {string} source path to copy.
998    * `dest` {string} destination path to copy to.
999    * Returns: {boolean|Promise}
1000  * `force` {boolean} overwrite existing file or directory. The copy
1001    operation will ignore errors if you set this to false and the destination
1002    exists. Use the `errorOnExist` option to change this behavior.
1003    **Default:** `true`.
1004  * `mode` {integer} modifiers for copy operation. **Default:** `0`.
1005    See `mode` flag of [`fsPromises.copyFile()`][].
1006  * `preserveTimestamps` {boolean} When `true` timestamps from `src` will
1007    be preserved. **Default:** `false`.
1008  * `recursive` {boolean} copy directories recursively **Default:** `false`
1009  * `verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will
1010    be skipped. **Default:** `false`
1011* Returns: {Promise} Fulfills with `undefined` upon success.
1012
1013Asynchronously copies the entire directory structure from `src` to `dest`,
1014including subdirectories and files.
1015
1016When copying a directory to another directory, globs are not supported and
1017behavior is similar to `cp dir1/ dir2/`.
1018
1019### `fsPromises.lchmod(path, mode)`
1020
1021<!-- YAML
1022deprecated: v10.0.0
1023-->
1024
1025* `path` {string|Buffer|URL}
1026* `mode` {integer}
1027* Returns: {Promise} Fulfills with `undefined` upon success.
1028
1029Changes the permissions on a symbolic link.
1030
1031This method is only implemented on macOS.
1032
1033### `fsPromises.lchown(path, uid, gid)`
1034
1035<!-- YAML
1036added: v10.0.0
1037changes:
1038  - version: v10.6.0
1039    pr-url: https://github.com/nodejs/node/pull/21498
1040    description: This API is no longer deprecated.
1041-->
1042
1043* `path` {string|Buffer|URL}
1044* `uid` {integer}
1045* `gid` {integer}
1046* Returns: {Promise}  Fulfills with `undefined` upon success.
1047
1048Changes the ownership on a symbolic link.
1049
1050### `fsPromises.lutimes(path, atime, mtime)`
1051
1052<!-- YAML
1053added:
1054  - v14.5.0
1055  - v12.19.0
1056-->
1057
1058* `path` {string|Buffer|URL}
1059* `atime` {number|string|Date}
1060* `mtime` {number|string|Date}
1061* Returns: {Promise}  Fulfills with `undefined` upon success.
1062
1063Changes the access and modification times of a file in the same way as
1064[`fsPromises.utimes()`][], with the difference that if the path refers to a
1065symbolic link, then the link is not dereferenced: instead, the timestamps of
1066the symbolic link itself are changed.
1067
1068### `fsPromises.link(existingPath, newPath)`
1069
1070<!-- YAML
1071added: v10.0.0
1072-->
1073
1074* `existingPath` {string|Buffer|URL}
1075* `newPath` {string|Buffer|URL}
1076* Returns: {Promise}  Fulfills with `undefined` upon success.
1077
1078Creates a new link from the `existingPath` to the `newPath`. See the POSIX
1079link(2) documentation for more detail.
1080
1081### `fsPromises.lstat(path[, options])`
1082
1083<!-- YAML
1084added: v10.0.0
1085changes:
1086  - version: v10.5.0
1087    pr-url: https://github.com/nodejs/node/pull/20220
1088    description: Accepts an additional `options` object to specify whether
1089                 the numeric values returned should be bigint.
1090-->
1091
1092* `path` {string|Buffer|URL}
1093* `options` {Object}
1094  * `bigint` {boolean} Whether the numeric values in the returned
1095    {fs.Stats} object should be `bigint`. **Default:** `false`.
1096* Returns: {Promise}  Fulfills with the {fs.Stats} object for the given
1097  symbolic link `path`.
1098
1099Equivalent to [`fsPromises.stat()`][] unless `path` refers to a symbolic link,
1100in which case the link itself is stat-ed, not the file that it refers to.
1101Refer to the POSIX lstat(2) document for more detail.
1102
1103### `fsPromises.mkdir(path[, options])`
1104
1105<!-- YAML
1106added: v10.0.0
1107-->
1108
1109* `path` {string|Buffer|URL}
1110* `options` {Object|integer}
1111  * `recursive` {boolean} **Default:** `false`
1112  * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
1113* Returns: {Promise} Upon success, fulfills with `undefined` if `recursive`
1114  is `false`, or the first directory path created if `recursive` is `true`.
1115
1116Asynchronously creates a directory.
1117
1118The optional `options` argument can be an integer specifying `mode` (permission
1119and sticky bits), or an object with a `mode` property and a `recursive`
1120property indicating whether parent directories should be created. Calling
1121`fsPromises.mkdir()` when `path` is a directory that exists results in a
1122rejection only when `recursive` is false.
1123
1124```mjs
1125import { mkdir } from 'node:fs/promises';
1126
1127try {
1128  const projectFolder = new URL('./test/project/', import.meta.url);
1129  const createDir = await mkdir(projectFolder, { recursive: true });
1130
1131  console.log(`created ${createDir}`);
1132} catch (err) {
1133  console.error(err.message);
1134}
1135```
1136
1137```cjs
1138const { mkdir } = require('node:fs/promises');
1139const { join } = require('node:path');
1140
1141async function makeDirectory() {
1142  const projectFolder = join(__dirname, 'test', 'project');
1143  const dirCreation = await mkdir(projectFolder, { recursive: true });
1144
1145  console.log(dirCreation);
1146  return dirCreation;
1147}
1148
1149makeDirectory().catch(console.error);
1150```
1151
1152### `fsPromises.mkdtemp(prefix[, options])`
1153
1154<!-- YAML
1155added: v10.0.0
1156changes:
1157  - version: v18.19.0
1158    pr-url: https://github.com/nodejs/node/pull/48828
1159    description: The `prefix` parameter now accepts buffers and URL.
1160  - version:
1161      - v16.5.0
1162      - v14.18.0
1163    pr-url: https://github.com/nodejs/node/pull/39028
1164    description: The `prefix` parameter now accepts an empty string.
1165-->
1166
1167* `prefix` {string|Buffer|URL}
1168* `options` {string|Object}
1169  * `encoding` {string} **Default:** `'utf8'`
1170* Returns: {Promise}  Fulfills with a string containing the file system path
1171  of the newly created temporary directory.
1172
1173Creates a unique temporary directory. A unique directory name is generated by
1174appending six random characters to the end of the provided `prefix`. Due to
1175platform inconsistencies, avoid trailing `X` characters in `prefix`. Some
1176platforms, notably the BSDs, can return more than six random characters, and
1177replace trailing `X` characters in `prefix` with random characters.
1178
1179The optional `options` argument can be a string specifying an encoding, or an
1180object with an `encoding` property specifying the character encoding to use.
1181
1182```mjs
1183import { mkdtemp } from 'node:fs/promises';
1184import { join } from 'node:path';
1185import { tmpdir } from 'node:os';
1186
1187try {
1188  await mkdtemp(join(tmpdir(), 'foo-'));
1189} catch (err) {
1190  console.error(err);
1191}
1192```
1193
1194The `fsPromises.mkdtemp()` method will append the six randomly selected
1195characters directly to the `prefix` string. For instance, given a directory
1196`/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the
1197`prefix` must end with a trailing platform-specific path separator
1198(`require('node:path').sep`).
1199
1200### `fsPromises.open(path, flags[, mode])`
1201
1202<!-- YAML
1203added: v10.0.0
1204changes:
1205  - version: v11.1.0
1206    pr-url: https://github.com/nodejs/node/pull/23767
1207    description: The `flags` argument is now optional and defaults to `'r'`.
1208-->
1209
1210* `path` {string|Buffer|URL}
1211* `flags` {string|number} See [support of file system `flags`][].
1212  **Default:** `'r'`.
1213* `mode` {string|integer} Sets the file mode (permission and sticky bits)
1214  if the file is created. **Default:** `0o666` (readable and writable)
1215* Returns: {Promise} Fulfills with a {FileHandle} object.
1216
1217Opens a {FileHandle}.
1218
1219Refer to the POSIX open(2) documentation for more detail.
1220
1221Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
1222by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains
1223a colon, Node.js will open a file system stream, as described by
1224[this MSDN page][MSDN-Using-Streams].
1225
1226### `fsPromises.opendir(path[, options])`
1227
1228<!-- YAML
1229added: v12.12.0
1230changes:
1231  - version: v18.17.0
1232    pr-url: https://github.com/nodejs/node/pull/41439
1233    description: Added `recursive` option.
1234  - version:
1235     - v13.1.0
1236     - v12.16.0
1237    pr-url: https://github.com/nodejs/node/pull/30114
1238    description: The `bufferSize` option was introduced.
1239-->
1240
1241* `path` {string|Buffer|URL}
1242* `options` {Object}
1243  * `encoding` {string|null} **Default:** `'utf8'`
1244  * `bufferSize` {number} Number of directory entries that are buffered
1245    internally when reading from the directory. Higher values lead to better
1246    performance but higher memory usage. **Default:** `32`
1247  * `recursive` {boolean} Resolved `Dir` will be an {AsyncIterable}
1248    containing all sub files and directories. **Default:** `false`
1249* Returns: {Promise}  Fulfills with an {fs.Dir}.
1250
1251Asynchronously open a directory for iterative scanning. See the POSIX
1252opendir(3) documentation for more detail.
1253
1254Creates an {fs.Dir}, which contains all further functions for reading from
1255and cleaning up the directory.
1256
1257The `encoding` option sets the encoding for the `path` while opening the
1258directory and subsequent read operations.
1259
1260Example using async iteration:
1261
1262```mjs
1263import { opendir } from 'node:fs/promises';
1264
1265try {
1266  const dir = await opendir('./');
1267  for await (const dirent of dir)
1268    console.log(dirent.name);
1269} catch (err) {
1270  console.error(err);
1271}
1272```
1273
1274When using the async iterator, the {fs.Dir} object will be automatically
1275closed after the iterator exits.
1276
1277### `fsPromises.readdir(path[, options])`
1278
1279<!-- YAML
1280added: v10.0.0
1281changes:
1282  - version: v18.17.0
1283    pr-url: https://github.com/nodejs/node/pull/41439
1284    description: Added `recursive` option.
1285  - version: v10.11.0
1286    pr-url: https://github.com/nodejs/node/pull/22020
1287    description: New option `withFileTypes` was added.
1288-->
1289
1290* `path` {string|Buffer|URL}
1291* `options` {string|Object}
1292  * `encoding` {string} **Default:** `'utf8'`
1293  * `withFileTypes` {boolean} **Default:** `false`
1294  * `recursive` {boolean} **Default:** `false`
1295* Returns: {Promise}  Fulfills with an array of the names of the files in
1296  the directory excluding `'.'` and `'..'`.
1297
1298Reads the contents of a directory.
1299
1300The optional `options` argument can be a string specifying an encoding, or an
1301object with an `encoding` property specifying the character encoding to use for
1302the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
1303will be passed as {Buffer} objects.
1304
1305If `options.withFileTypes` is set to `true`, the resolved array will contain
1306{fs.Dirent} objects.
1307
1308```mjs
1309import { readdir } from 'node:fs/promises';
1310
1311try {
1312  const files = await readdir(path);
1313  for (const file of files)
1314    console.log(file);
1315} catch (err) {
1316  console.error(err);
1317}
1318```
1319
1320### `fsPromises.readFile(path[, options])`
1321
1322<!-- YAML
1323added: v10.0.0
1324changes:
1325  - version:
1326    - v15.2.0
1327    - v14.17.0
1328    pr-url: https://github.com/nodejs/node/pull/35911
1329    description: The options argument may include an AbortSignal to abort an
1330                 ongoing readFile request.
1331-->
1332
1333* `path` {string|Buffer|URL|FileHandle} filename or `FileHandle`
1334* `options` {Object|string}
1335  * `encoding` {string|null} **Default:** `null`
1336  * `flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.
1337  * `signal` {AbortSignal} allows aborting an in-progress readFile
1338* Returns: {Promise}  Fulfills with the contents of the file.
1339
1340Asynchronously reads the entire contents of a file.
1341
1342If no encoding is specified (using `options.encoding`), the data is returned
1343as a {Buffer} object. Otherwise, the data will be a string.
1344
1345If `options` is a string, then it specifies the encoding.
1346
1347When the `path` is a directory, the behavior of `fsPromises.readFile()` is
1348platform-specific. On macOS, Linux, and Windows, the promise will be rejected
1349with an error. On FreeBSD, a representation of the directory's contents will be
1350returned.
1351
1352An example of reading a `package.json` file located in the same directory of the
1353running code:
1354
1355```mjs
1356import { readFile } from 'node:fs/promises';
1357try {
1358  const filePath = new URL('./package.json', import.meta.url);
1359  const contents = await readFile(filePath, { encoding: 'utf8' });
1360  console.log(contents);
1361} catch (err) {
1362  console.error(err.message);
1363}
1364```
1365
1366```cjs
1367const { readFile } = require('node:fs/promises');
1368const { resolve } = require('node:path');
1369async function logFile() {
1370  try {
1371    const filePath = resolve('./package.json');
1372    const contents = await readFile(filePath, { encoding: 'utf8' });
1373    console.log(contents);
1374  } catch (err) {
1375    console.error(err.message);
1376  }
1377}
1378logFile();
1379```
1380
1381It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a
1382request is aborted the promise returned is rejected with an `AbortError`:
1383
1384```mjs
1385import { readFile } from 'node:fs/promises';
1386
1387try {
1388  const controller = new AbortController();
1389  const { signal } = controller;
1390  const promise = readFile(fileName, { signal });
1391
1392  // Abort the request before the promise settles.
1393  controller.abort();
1394
1395  await promise;
1396} catch (err) {
1397  // When a request is aborted - err is an AbortError
1398  console.error(err);
1399}
1400```
1401
1402Aborting an ongoing request does not abort individual operating
1403system requests but rather the internal buffering `fs.readFile` performs.
1404
1405Any specified {FileHandle} has to support reading.
1406
1407### `fsPromises.readlink(path[, options])`
1408
1409<!-- YAML
1410added: v10.0.0
1411-->
1412
1413* `path` {string|Buffer|URL}
1414* `options` {string|Object}
1415  * `encoding` {string} **Default:** `'utf8'`
1416* Returns: {Promise} Fulfills with the `linkString` upon success.
1417
1418Reads the contents of the symbolic link referred to by `path`. See the POSIX
1419readlink(2) documentation for more detail. The promise is resolved with the
1420`linkString` upon success.
1421
1422The optional `options` argument can be a string specifying an encoding, or an
1423object with an `encoding` property specifying the character encoding to use for
1424the link path returned. If the `encoding` is set to `'buffer'`, the link path
1425returned will be passed as a {Buffer} object.
1426
1427### `fsPromises.realpath(path[, options])`
1428
1429<!-- YAML
1430added: v10.0.0
1431-->
1432
1433* `path` {string|Buffer|URL}
1434* `options` {string|Object}
1435  * `encoding` {string} **Default:** `'utf8'`
1436* Returns: {Promise}  Fulfills with the resolved path upon success.
1437
1438Determines the actual location of `path` using the same semantics as the
1439`fs.realpath.native()` function.
1440
1441Only paths that can be converted to UTF8 strings are supported.
1442
1443The optional `options` argument can be a string specifying an encoding, or an
1444object with an `encoding` property specifying the character encoding to use for
1445the path. If the `encoding` is set to `'buffer'`, the path returned will be
1446passed as a {Buffer} object.
1447
1448On Linux, when Node.js is linked against musl libc, the procfs file system must
1449be mounted on `/proc` in order for this function to work. Glibc does not have
1450this restriction.
1451
1452### `fsPromises.rename(oldPath, newPath)`
1453
1454<!-- YAML
1455added: v10.0.0
1456-->
1457
1458* `oldPath` {string|Buffer|URL}
1459* `newPath` {string|Buffer|URL}
1460* Returns: {Promise} Fulfills with `undefined` upon success.
1461
1462Renames `oldPath` to `newPath`.
1463
1464### `fsPromises.rmdir(path[, options])`
1465
1466<!-- YAML
1467added: v10.0.0
1468changes:
1469  - version: v16.0.0
1470    pr-url: https://github.com/nodejs/node/pull/37216
1471    description: "Using `fsPromises.rmdir(path, { recursive: true })` on a `path`
1472                 that is a file is no longer permitted and results in an
1473                 `ENOENT` error on Windows and an `ENOTDIR` error on POSIX."
1474  - version: v16.0.0
1475    pr-url: https://github.com/nodejs/node/pull/37216
1476    description: "Using `fsPromises.rmdir(path, { recursive: true })` on a `path`
1477                 that does not exist is no longer permitted and results in a
1478                 `ENOENT` error."
1479  - version: v16.0.0
1480    pr-url: https://github.com/nodejs/node/pull/37302
1481    description: The `recursive` option is deprecated, using it triggers a
1482                 deprecation warning.
1483  - version: v14.14.0
1484    pr-url: https://github.com/nodejs/node/pull/35579
1485    description: The `recursive` option is deprecated, use `fsPromises.rm` instead.
1486  - version:
1487     - v13.3.0
1488     - v12.16.0
1489    pr-url: https://github.com/nodejs/node/pull/30644
1490    description: The `maxBusyTries` option is renamed to `maxRetries`, and its
1491                 default is 0. The `emfileWait` option has been removed, and
1492                 `EMFILE` errors use the same retry logic as other errors. The
1493                 `retryDelay` option is now supported. `ENFILE` errors are now
1494                 retried.
1495  - version: v12.10.0
1496    pr-url: https://github.com/nodejs/node/pull/29168
1497    description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
1498                  now supported.
1499-->
1500
1501* `path` {string|Buffer|URL}
1502* `options` {Object}
1503  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
1504    `EPERM` error is encountered, Node.js retries the operation with a linear
1505    backoff wait of `retryDelay` milliseconds longer on each try. This option
1506    represents the number of retries. This option is ignored if the `recursive`
1507    option is not `true`. **Default:** `0`.
1508  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
1509    recursive mode, operations are retried on failure. **Default:** `false`.
1510    **Deprecated.**
1511  * `retryDelay` {integer} The amount of time in milliseconds to wait between
1512    retries. This option is ignored if the `recursive` option is not `true`.
1513    **Default:** `100`.
1514* Returns: {Promise} Fulfills with `undefined` upon success.
1515
1516Removes the directory identified by `path`.
1517
1518Using `fsPromises.rmdir()` on a file (not a directory) results in the
1519promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`
1520error on POSIX.
1521
1522To get a behavior similar to the `rm -rf` Unix command, use
1523[`fsPromises.rm()`][] with options `{ recursive: true, force: true }`.
1524
1525### `fsPromises.rm(path[, options])`
1526
1527<!-- YAML
1528added: v14.14.0
1529-->
1530
1531* `path` {string|Buffer|URL}
1532* `options` {Object}
1533  * `force` {boolean} When `true`, exceptions will be ignored if `path` does
1534    not exist. **Default:** `false`.
1535  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
1536    `EPERM` error is encountered, Node.js will retry the operation with a linear
1537    backoff wait of `retryDelay` milliseconds longer on each try. This option
1538    represents the number of retries. This option is ignored if the `recursive`
1539    option is not `true`. **Default:** `0`.
1540  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
1541    recursive mode operations are retried on failure. **Default:** `false`.
1542  * `retryDelay` {integer} The amount of time in milliseconds to wait between
1543    retries. This option is ignored if the `recursive` option is not `true`.
1544    **Default:** `100`.
1545* Returns: {Promise} Fulfills with `undefined` upon success.
1546
1547Removes files and directories (modeled on the standard POSIX `rm` utility).
1548
1549### `fsPromises.stat(path[, options])`
1550
1551<!-- YAML
1552added: v10.0.0
1553changes:
1554  - version: v10.5.0
1555    pr-url: https://github.com/nodejs/node/pull/20220
1556    description: Accepts an additional `options` object to specify whether
1557                 the numeric values returned should be bigint.
1558-->
1559
1560* `path` {string|Buffer|URL}
1561* `options` {Object}
1562  * `bigint` {boolean} Whether the numeric values in the returned
1563    {fs.Stats} object should be `bigint`. **Default:** `false`.
1564* Returns: {Promise}  Fulfills with the {fs.Stats} object for the
1565  given `path`.
1566
1567### `fsPromises.statfs(path[, options])`
1568
1569<!-- YAML
1570added: v18.15.0
1571-->
1572
1573* `path` {string|Buffer|URL}
1574* `options` {Object}
1575  * `bigint` {boolean} Whether the numeric values in the returned
1576    {fs.StatFs} object should be `bigint`. **Default:** `false`.
1577* Returns: {Promise} Fulfills with the {fs.StatFs} object for the
1578  given `path`.
1579
1580### `fsPromises.symlink(target, path[, type])`
1581
1582<!-- YAML
1583added: v10.0.0
1584-->
1585
1586* `target` {string|Buffer|URL}
1587* `path` {string|Buffer|URL}
1588* `type` {string} **Default:** `'file'`
1589* Returns: {Promise} Fulfills with `undefined` upon success.
1590
1591Creates a symbolic link.
1592
1593The `type` argument is only used on Windows platforms and can be one of `'dir'`,
1594`'file'`, or `'junction'`. Windows junction points require the destination path
1595to be absolute. When using `'junction'`, the `target` argument will
1596automatically be normalized to absolute path. Junction points on NTFS volumes
1597can only point to directories.
1598
1599### `fsPromises.truncate(path[, len])`
1600
1601<!-- YAML
1602added: v10.0.0
1603-->
1604
1605* `path` {string|Buffer|URL}
1606* `len` {integer} **Default:** `0`
1607* Returns: {Promise} Fulfills with `undefined` upon success.
1608
1609Truncates (shortens or extends the length) of the content at `path` to `len`
1610bytes.
1611
1612### `fsPromises.unlink(path)`
1613
1614<!-- YAML
1615added: v10.0.0
1616-->
1617
1618* `path` {string|Buffer|URL}
1619* Returns: {Promise} Fulfills with `undefined` upon success.
1620
1621If `path` refers to a symbolic link, then the link is removed without affecting
1622the file or directory to which that link refers. If the `path` refers to a file
1623path that is not a symbolic link, the file is deleted. See the POSIX unlink(2)
1624documentation for more detail.
1625
1626### `fsPromises.utimes(path, atime, mtime)`
1627
1628<!-- YAML
1629added: v10.0.0
1630-->
1631
1632* `path` {string|Buffer|URL}
1633* `atime` {number|string|Date}
1634* `mtime` {number|string|Date}
1635* Returns: {Promise} Fulfills with `undefined` upon success.
1636
1637Change the file system timestamps of the object referenced by `path`.
1638
1639The `atime` and `mtime` arguments follow these rules:
1640
1641* Values can be either numbers representing Unix epoch time, `Date`s, or a
1642  numeric string like `'123456789.0'`.
1643* If the value can not be converted to a number, or is `NaN`, `Infinity`, or
1644  `-Infinity`, an `Error` will be thrown.
1645
1646### `fsPromises.watch(filename[, options])`
1647
1648<!-- YAML
1649added:
1650  - v15.9.0
1651  - v14.18.0
1652-->
1653
1654* `filename` {string|Buffer|URL}
1655* `options` {string|Object}
1656  * `persistent` {boolean} Indicates whether the process should continue to run
1657    as long as files are being watched. **Default:** `true`.
1658  * `recursive` {boolean} Indicates whether all subdirectories should be
1659    watched, or only the current directory. This applies when a directory is
1660    specified, and only on supported platforms (See [caveats][]). **Default:**
1661    `false`.
1662  * `encoding` {string} Specifies the character encoding to be used for the
1663    filename passed to the listener. **Default:** `'utf8'`.
1664  * `signal` {AbortSignal} An {AbortSignal} used to signal when the watcher
1665    should stop.
1666* Returns: {AsyncIterator} of objects with the properties:
1667  * `eventType` {string} The type of change
1668  * `filename` {string|Buffer|null} The name of the file changed.
1669
1670Returns an async iterator that watches for changes on `filename`, where `filename`
1671is either a file or a directory.
1672
1673```js
1674const { watch } = require('node:fs/promises');
1675
1676const ac = new AbortController();
1677const { signal } = ac;
1678setTimeout(() => ac.abort(), 10000);
1679
1680(async () => {
1681  try {
1682    const watcher = watch(__filename, { signal });
1683    for await (const event of watcher)
1684      console.log(event);
1685  } catch (err) {
1686    if (err.name === 'AbortError')
1687      return;
1688    throw err;
1689  }
1690})();
1691```
1692
1693On most platforms, `'rename'` is emitted whenever a filename appears or
1694disappears in the directory.
1695
1696All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`.
1697
1698### `fsPromises.writeFile(file, data[, options])`
1699
1700<!-- YAML
1701added: v10.0.0
1702changes:
1703  - version:
1704      - v15.14.0
1705      - v14.18.0
1706    pr-url: https://github.com/nodejs/node/pull/37490
1707    description: The `data` argument supports `AsyncIterable`, `Iterable`, and `Stream`.
1708  - version:
1709      - v15.2.0
1710      - v14.17.0
1711    pr-url: https://github.com/nodejs/node/pull/35993
1712    description: The options argument may include an AbortSignal to abort an
1713                 ongoing writeFile request.
1714  - version: v14.0.0
1715    pr-url: https://github.com/nodejs/node/pull/31030
1716    description: The `data` parameter won't coerce unsupported input to
1717                 strings anymore.
1718-->
1719
1720* `file` {string|Buffer|URL|FileHandle} filename or `FileHandle`
1721* `data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream}
1722* `options` {Object|string}
1723  * `encoding` {string|null} **Default:** `'utf8'`
1724  * `mode` {integer} **Default:** `0o666`
1725  * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.
1726  * `signal` {AbortSignal} allows aborting an in-progress writeFile
1727* Returns: {Promise} Fulfills with `undefined` upon success.
1728
1729Asynchronously writes data to a file, replacing the file if it already exists.
1730`data` can be a string, a buffer, an {AsyncIterable}, or an {Iterable} object.
1731
1732The `encoding` option is ignored if `data` is a buffer.
1733
1734If `options` is a string, then it specifies the encoding.
1735
1736The `mode` option only affects the newly created file. See [`fs.open()`][]
1737for more details.
1738
1739Any specified {FileHandle} has to support writing.
1740
1741It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
1742without waiting for the promise to be settled.
1743
1744Similarly to `fsPromises.readFile` - `fsPromises.writeFile` is a convenience
1745method that performs multiple `write` calls internally to write the buffer
1746passed to it. For performance sensitive code consider using
1747[`fs.createWriteStream()`][] or [`filehandle.createWriteStream()`][].
1748
1749It is possible to use an {AbortSignal} to cancel an `fsPromises.writeFile()`.
1750Cancelation is "best effort", and some amount of data is likely still
1751to be written.
1752
1753```mjs
1754import { writeFile } from 'node:fs/promises';
1755import { Buffer } from 'node:buffer';
1756
1757try {
1758  const controller = new AbortController();
1759  const { signal } = controller;
1760  const data = new Uint8Array(Buffer.from('Hello Node.js'));
1761  const promise = writeFile('message.txt', data, { signal });
1762
1763  // Abort the request before the promise settles.
1764  controller.abort();
1765
1766  await promise;
1767} catch (err) {
1768  // When a request is aborted - err is an AbortError
1769  console.error(err);
1770}
1771```
1772
1773Aborting an ongoing request does not abort individual operating
1774system requests but rather the internal buffering `fs.writeFile` performs.
1775
1776### `fsPromises.constants`
1777
1778<!-- YAML
1779added:
1780  - v18.4.0
1781  - v16.17.0
1782-->
1783
1784* {Object}
1785
1786Returns an object containing commonly used constants for file system
1787operations. The object is the same as `fs.constants`. See [FS constants][]
1788for more details.
1789
1790## Callback API
1791
1792The callback APIs perform all operations asynchronously, without blocking the
1793event loop, then invoke a callback function upon completion or error.
1794
1795The callback APIs use the underlying Node.js threadpool to perform file
1796system operations off the event loop thread. These operations are not
1797synchronized or threadsafe. Care must be taken when performing multiple
1798concurrent modifications on the same file or data corruption may occur.
1799
1800### `fs.access(path[, mode], callback)`
1801
1802<!-- YAML
1803added: v0.11.15
1804changes:
1805  - version: v18.0.0
1806    pr-url: https://github.com/nodejs/node/pull/41678
1807    description: Passing an invalid callback to the `callback` argument
1808                 now throws `ERR_INVALID_ARG_TYPE` instead of
1809                 `ERR_INVALID_CALLBACK`.
1810  - version: v7.6.0
1811    pr-url: https://github.com/nodejs/node/pull/10739
1812    description: The `path` parameter can be a WHATWG `URL` object using `file:`
1813                 protocol.
1814  - version: v6.3.0
1815    pr-url: https://github.com/nodejs/node/pull/6534
1816    description: The constants like `fs.R_OK`, etc which were present directly
1817                 on `fs` were moved into `fs.constants` as a soft deprecation.
1818                 Thus for Node.js `< v6.3.0` use `fs`
1819                 to access those constants, or
1820                 do something like `(fs.constants || fs).R_OK` to work with all
1821                 versions.
1822-->
1823
1824* `path` {string|Buffer|URL}
1825* `mode` {integer} **Default:** `fs.constants.F_OK`
1826* `callback` {Function}
1827  * `err` {Error}
1828
1829Tests a user's permissions for the file or directory specified by `path`.
1830The `mode` argument is an optional integer that specifies the accessibility
1831checks to be performed. `mode` should be either the value `fs.constants.F_OK`
1832or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,
1833`fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.
1834`fs.constants.W_OK | fs.constants.R_OK`). Check [File access constants][] for
1835possible values of `mode`.
1836
1837The final argument, `callback`, is a callback function that is invoked with
1838a possible error argument. If any of the accessibility checks fail, the error
1839argument will be an `Error` object. The following examples check if
1840`package.json` exists, and if it is readable or writable.
1841
1842```mjs
1843import { access, constants } from 'node:fs';
1844
1845const file = 'package.json';
1846
1847// Check if the file exists in the current directory.
1848access(file, constants.F_OK, (err) => {
1849  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
1850});
1851
1852// Check if the file is readable.
1853access(file, constants.R_OK, (err) => {
1854  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
1855});
1856
1857// Check if the file is writable.
1858access(file, constants.W_OK, (err) => {
1859  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
1860});
1861
1862// Check if the file is readable and writable.
1863access(file, constants.R_OK | constants.W_OK, (err) => {
1864  console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
1865});
1866```
1867
1868Do not use `fs.access()` to check for the accessibility of a file before calling
1869`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing
1870so introduces a race condition, since other processes may change the file's
1871state between the two calls. Instead, user code should open/read/write the
1872file directly and handle the error raised if the file is not accessible.
1873
1874**write (NOT RECOMMENDED)**
1875
1876```mjs
1877import { access, open, close } from 'node:fs';
1878
1879access('myfile', (err) => {
1880  if (!err) {
1881    console.error('myfile already exists');
1882    return;
1883  }
1884
1885  open('myfile', 'wx', (err, fd) => {
1886    if (err) throw err;
1887
1888    try {
1889      writeMyData(fd);
1890    } finally {
1891      close(fd, (err) => {
1892        if (err) throw err;
1893      });
1894    }
1895  });
1896});
1897```
1898
1899**write (RECOMMENDED)**
1900
1901```mjs
1902import { open, close } from 'node:fs';
1903
1904open('myfile', 'wx', (err, fd) => {
1905  if (err) {
1906    if (err.code === 'EEXIST') {
1907      console.error('myfile already exists');
1908      return;
1909    }
1910
1911    throw err;
1912  }
1913
1914  try {
1915    writeMyData(fd);
1916  } finally {
1917    close(fd, (err) => {
1918      if (err) throw err;
1919    });
1920  }
1921});
1922```
1923
1924**read (NOT RECOMMENDED)**
1925
1926```mjs
1927import { access, open, close } from 'node:fs';
1928access('myfile', (err) => {
1929  if (err) {
1930    if (err.code === 'ENOENT') {
1931      console.error('myfile does not exist');
1932      return;
1933    }
1934
1935    throw err;
1936  }
1937
1938  open('myfile', 'r', (err, fd) => {
1939    if (err) throw err;
1940
1941    try {
1942      readMyData(fd);
1943    } finally {
1944      close(fd, (err) => {
1945        if (err) throw err;
1946      });
1947    }
1948  });
1949});
1950```
1951
1952**read (RECOMMENDED)**
1953
1954```mjs
1955import { open, close } from 'node:fs';
1956
1957open('myfile', 'r', (err, fd) => {
1958  if (err) {
1959    if (err.code === 'ENOENT') {
1960      console.error('myfile does not exist');
1961      return;
1962    }
1963
1964    throw err;
1965  }
1966
1967  try {
1968    readMyData(fd);
1969  } finally {
1970    close(fd, (err) => {
1971      if (err) throw err;
1972    });
1973  }
1974});
1975```
1976
1977The "not recommended" examples above check for accessibility and then use the
1978file; the "recommended" examples are better because they use the file directly
1979and handle the error, if any.
1980
1981In general, check for the accessibility of a file only if the file will not be
1982used directly, for example when its accessibility is a signal from another
1983process.
1984
1985On Windows, access-control policies (ACLs) on a directory may limit access to
1986a file or directory. The `fs.access()` function, however, does not check the
1987ACL and therefore may report that a path is accessible even if the ACL restricts
1988the user from reading or writing to it.
1989
1990### `fs.appendFile(path, data[, options], callback)`
1991
1992<!-- YAML
1993added: v0.6.7
1994changes:
1995  - version: v18.0.0
1996    pr-url: https://github.com/nodejs/node/pull/41678
1997    description: Passing an invalid callback to the `callback` argument
1998                 now throws `ERR_INVALID_ARG_TYPE` instead of
1999                 `ERR_INVALID_CALLBACK`.
2000  - version: v10.0.0
2001    pr-url: https://github.com/nodejs/node/pull/12562
2002    description: The `callback` parameter is no longer optional. Not passing
2003                 it will throw a `TypeError` at runtime.
2004  - version: v7.0.0
2005    pr-url: https://github.com/nodejs/node/pull/7897
2006    description: The `callback` parameter is no longer optional. Not passing
2007                 it will emit a deprecation warning with id DEP0013.
2008  - version: v7.0.0
2009    pr-url: https://github.com/nodejs/node/pull/7831
2010    description: The passed `options` object will never be modified.
2011  - version: v5.0.0
2012    pr-url: https://github.com/nodejs/node/pull/3163
2013    description: The `file` parameter can be a file descriptor now.
2014-->
2015
2016* `path` {string|Buffer|URL|number} filename or file descriptor
2017* `data` {string|Buffer}
2018* `options` {Object|string}
2019  * `encoding` {string|null} **Default:** `'utf8'`
2020  * `mode` {integer} **Default:** `0o666`
2021  * `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
2022* `callback` {Function}
2023  * `err` {Error}
2024
2025Asynchronously append data to a file, creating the file if it does not yet
2026exist. `data` can be a string or a {Buffer}.
2027
2028The `mode` option only affects the newly created file. See [`fs.open()`][]
2029for more details.
2030
2031```mjs
2032import { appendFile } from 'node:fs';
2033
2034appendFile('message.txt', 'data to append', (err) => {
2035  if (err) throw err;
2036  console.log('The "data to append" was appended to file!');
2037});
2038```
2039
2040If `options` is a string, then it specifies the encoding:
2041
2042```mjs
2043import { appendFile } from 'node:fs';
2044
2045appendFile('message.txt', 'data to append', 'utf8', callback);
2046```
2047
2048The `path` may be specified as a numeric file descriptor that has been opened
2049for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
2050not be closed automatically.
2051
2052```mjs
2053import { open, close, appendFile } from 'node:fs';
2054
2055function closeFd(fd) {
2056  close(fd, (err) => {
2057    if (err) throw err;
2058  });
2059}
2060
2061open('message.txt', 'a', (err, fd) => {
2062  if (err) throw err;
2063
2064  try {
2065    appendFile(fd, 'data to append', 'utf8', (err) => {
2066      closeFd(fd);
2067      if (err) throw err;
2068    });
2069  } catch (err) {
2070    closeFd(fd);
2071    throw err;
2072  }
2073});
2074```
2075
2076### `fs.chmod(path, mode, callback)`
2077
2078<!-- YAML
2079added: v0.1.30
2080changes:
2081  - version: v18.0.0
2082    pr-url: https://github.com/nodejs/node/pull/41678
2083    description: Passing an invalid callback to the `callback` argument
2084                 now throws `ERR_INVALID_ARG_TYPE` instead of
2085                 `ERR_INVALID_CALLBACK`.
2086  - version: v10.0.0
2087    pr-url: https://github.com/nodejs/node/pull/12562
2088    description: The `callback` parameter is no longer optional. Not passing
2089                 it will throw a `TypeError` at runtime.
2090  - version: v7.6.0
2091    pr-url: https://github.com/nodejs/node/pull/10739
2092    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2093                 protocol.
2094  - version: v7.0.0
2095    pr-url: https://github.com/nodejs/node/pull/7897
2096    description: The `callback` parameter is no longer optional. Not passing
2097                 it will emit a deprecation warning with id DEP0013.
2098-->
2099
2100* `path` {string|Buffer|URL}
2101* `mode` {string|integer}
2102* `callback` {Function}
2103  * `err` {Error}
2104
2105Asynchronously changes the permissions of a file. No arguments other than a
2106possible exception are given to the completion callback.
2107
2108See the POSIX chmod(2) documentation for more detail.
2109
2110```mjs
2111import { chmod } from 'node:fs';
2112
2113chmod('my_file.txt', 0o775, (err) => {
2114  if (err) throw err;
2115  console.log('The permissions for file "my_file.txt" have been changed!');
2116});
2117```
2118
2119#### File modes
2120
2121The `mode` argument used in both the `fs.chmod()` and `fs.chmodSync()`
2122methods is a numeric bitmask created using a logical OR of the following
2123constants:
2124
2125| Constant               | Octal   | Description              |
2126| ---------------------- | ------- | ------------------------ |
2127| `fs.constants.S_IRUSR` | `0o400` | read by owner            |
2128| `fs.constants.S_IWUSR` | `0o200` | write by owner           |
2129| `fs.constants.S_IXUSR` | `0o100` | execute/search by owner  |
2130| `fs.constants.S_IRGRP` | `0o40`  | read by group            |
2131| `fs.constants.S_IWGRP` | `0o20`  | write by group           |
2132| `fs.constants.S_IXGRP` | `0o10`  | execute/search by group  |
2133| `fs.constants.S_IROTH` | `0o4`   | read by others           |
2134| `fs.constants.S_IWOTH` | `0o2`   | write by others          |
2135| `fs.constants.S_IXOTH` | `0o1`   | execute/search by others |
2136
2137An easier method of constructing the `mode` is to use a sequence of three
2138octal digits (e.g. `765`). The left-most digit (`7` in the example), specifies
2139the permissions for the file owner. The middle digit (`6` in the example),
2140specifies permissions for the group. The right-most digit (`5` in the example),
2141specifies the permissions for others.
2142
2143| Number | Description              |
2144| ------ | ------------------------ |
2145| `7`    | read, write, and execute |
2146| `6`    | read and write           |
2147| `5`    | read and execute         |
2148| `4`    | read only                |
2149| `3`    | write and execute        |
2150| `2`    | write only               |
2151| `1`    | execute only             |
2152| `0`    | no permission            |
2153
2154For example, the octal value `0o765` means:
2155
2156* The owner may read, write, and execute the file.
2157* The group may read and write the file.
2158* Others may read and execute the file.
2159
2160When using raw numbers where file modes are expected, any value larger than
2161`0o777` may result in platform-specific behaviors that are not supported to work
2162consistently. Therefore constants like `S_ISVTX`, `S_ISGID`, or `S_ISUID` are
2163not exposed in `fs.constants`.
2164
2165Caveats: on Windows only the write permission can be changed, and the
2166distinction among the permissions of group, owner, or others is not
2167implemented.
2168
2169### `fs.chown(path, uid, gid, callback)`
2170
2171<!-- YAML
2172added: v0.1.97
2173changes:
2174  - version: v18.0.0
2175    pr-url: https://github.com/nodejs/node/pull/41678
2176    description: Passing an invalid callback to the `callback` argument
2177                 now throws `ERR_INVALID_ARG_TYPE` instead of
2178                 `ERR_INVALID_CALLBACK`.
2179  - version: v10.0.0
2180    pr-url: https://github.com/nodejs/node/pull/12562
2181    description: The `callback` parameter is no longer optional. Not passing
2182                 it will throw a `TypeError` at runtime.
2183  - version: v7.6.0
2184    pr-url: https://github.com/nodejs/node/pull/10739
2185    description: The `path` parameter can be a WHATWG `URL` object using `file:`
2186                 protocol.
2187  - version: v7.0.0
2188    pr-url: https://github.com/nodejs/node/pull/7897
2189    description: The `callback` parameter is no longer optional. Not passing
2190                 it will emit a deprecation warning with id DEP0013.
2191-->
2192
2193* `path` {string|Buffer|URL}
2194* `uid` {integer}
2195* `gid` {integer}
2196* `callback` {Function}
2197  * `err` {Error}
2198
2199Asynchronously changes owner and group of a file. No arguments other than a
2200possible exception are given to the completion callback.
2201
2202See the POSIX chown(2) documentation for more detail.
2203
2204### `fs.close(fd[, callback])`
2205
2206<!-- YAML
2207added: v0.0.2
2208changes:
2209  - version: v18.0.0
2210    pr-url: https://github.com/nodejs/node/pull/41678
2211    description: Passing an invalid callback to the `callback` argument
2212                 now throws `ERR_INVALID_ARG_TYPE` instead of
2213                 `ERR_INVALID_CALLBACK`.
2214  - version:
2215      - v15.9.0
2216      - v14.17.0
2217    pr-url: https://github.com/nodejs/node/pull/37174
2218    description: A default callback is now used if one is not provided.
2219  - version: v10.0.0
2220    pr-url: https://github.com/nodejs/node/pull/12562
2221    description: The `callback` parameter is no longer optional. Not passing
2222                 it will throw a `TypeError` at runtime.
2223  - version: v7.0.0
2224    pr-url: https://github.com/nodejs/node/pull/7897
2225    description: The `callback` parameter is no longer optional. Not passing
2226                 it will emit a deprecation warning with id DEP0013.
2227-->
2228
2229* `fd` {integer}
2230* `callback` {Function}
2231  * `err` {Error}
2232
2233Closes the file descriptor. No arguments other than a possible exception are
2234given to the completion callback.
2235
2236Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
2237through any other `fs` operation may lead to undefined behavior.
2238
2239See the POSIX close(2) documentation for more detail.
2240
2241### `fs.copyFile(src, dest[, mode], callback)`
2242
2243<!-- YAML
2244added: v8.5.0
2245changes:
2246  - version: v18.0.0
2247    pr-url: https://github.com/nodejs/node/pull/41678
2248    description: Passing an invalid callback to the `callback` argument
2249                 now throws `ERR_INVALID_ARG_TYPE` instead of
2250                 `ERR_INVALID_CALLBACK`.
2251  - version: v14.0.0
2252    pr-url: https://github.com/nodejs/node/pull/27044
2253    description: Changed `flags` argument to `mode` and imposed
2254                 stricter type validation.
2255-->
2256
2257* `src` {string|Buffer|URL} source filename to copy
2258* `dest` {string|Buffer|URL} destination filename of the copy operation
2259* `mode` {integer} modifiers for copy operation. **Default:** `0`.
2260* `callback` {Function}
2261
2262Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
2263already exists. No arguments other than a possible exception are given to the
2264callback function. Node.js makes no guarantees about the atomicity of the copy
2265operation. If an error occurs after the destination file has been opened for
2266writing, Node.js will attempt to remove the destination.
2267
2268`mode` is an optional integer that specifies the behavior
2269of the copy operation. It is possible to create a mask consisting of the bitwise
2270OR of two or more values (e.g.
2271`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
2272
2273* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
2274  exists.
2275* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
2276  copy-on-write reflink. If the platform does not support copy-on-write, then a
2277  fallback copy mechanism is used.
2278* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
2279  create a copy-on-write reflink. If the platform does not support
2280  copy-on-write, then the operation will fail.
2281
2282```mjs
2283import { copyFile, constants } from 'node:fs';
2284
2285function callback(err) {
2286  if (err) throw err;
2287  console.log('source.txt was copied to destination.txt');
2288}
2289
2290// destination.txt will be created or overwritten by default.
2291copyFile('source.txt', 'destination.txt', callback);
2292
2293// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
2294copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
2295```
2296
2297### `fs.cp(src, dest[, options], callback)`
2298
2299<!-- YAML
2300added: v16.7.0
2301changes:
2302  - version: v18.17.0
2303    pr-url: https://github.com/nodejs/node/pull/47084
2304    description: Accept an additional `mode` option to specify
2305                 the copy behavior as the `mode` argument of `fs.copyFile()`.
2306  - version: v18.0.0
2307    pr-url: https://github.com/nodejs/node/pull/41678
2308    description: Passing an invalid callback to the `callback` argument
2309                 now throws `ERR_INVALID_ARG_TYPE` instead of
2310                 `ERR_INVALID_CALLBACK`.
2311  - version: v17.6.0
2312    pr-url: https://github.com/nodejs/node/pull/41819
2313    description: Accepts an additional `verbatimSymlinks` option to specify
2314                 whether to perform path resolution for symlinks.
2315-->
2316
2317> Stability: 1 - Experimental
2318
2319* `src` {string|URL} source path to copy.
2320* `dest` {string|URL} destination path to copy to.
2321* `options` {Object}
2322  * `dereference` {boolean} dereference symlinks. **Default:** `false`.
2323  * `errorOnExist` {boolean} when `force` is `false`, and the destination
2324    exists, throw an error. **Default:** `false`.
2325  * `filter` {Function} Function to filter copied files/directories. Return
2326    `true` to copy the item, `false` to ignore it. When ignoring a directory,
2327    all of its contents will be skipped as well. Can also return a `Promise`
2328    that resolves to `true` or `false` **Default:** `undefined`.
2329    * `src` {string} source path to copy.
2330    * `dest` {string} destination path to copy to.
2331    * Returns: {boolean|Promise}
2332  * `force` {boolean} overwrite existing file or directory. The copy
2333    operation will ignore errors if you set this to false and the destination
2334    exists. Use the `errorOnExist` option to change this behavior.
2335    **Default:** `true`.
2336  * `mode` {integer} modifiers for copy operation. **Default:** `0`.
2337    See `mode` flag of [`fs.copyFile()`][].
2338  * `preserveTimestamps` {boolean} When `true` timestamps from `src` will
2339    be preserved. **Default:** `false`.
2340  * `recursive` {boolean} copy directories recursively **Default:** `false`
2341  * `verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will
2342    be skipped. **Default:** `false`
2343* `callback` {Function}
2344
2345Asynchronously copies the entire directory structure from `src` to `dest`,
2346including subdirectories and files.
2347
2348When copying a directory to another directory, globs are not supported and
2349behavior is similar to `cp dir1/ dir2/`.
2350
2351### `fs.createReadStream(path[, options])`
2352
2353<!-- YAML
2354added: v0.1.31
2355changes:
2356  - version: v16.10.0
2357    pr-url: https://github.com/nodejs/node/pull/40013
2358    description: The `fs` option does not need `open` method if an `fd` was provided.
2359  - version: v16.10.0
2360    pr-url: https://github.com/nodejs/node/pull/40013
2361    description: The `fs` option does not need `close` method if `autoClose` is `false`.
2362  - version: v15.5.0
2363    pr-url: https://github.com/nodejs/node/pull/36431
2364    description: Add support for `AbortSignal`.
2365  - version:
2366     - v15.4.0
2367    pr-url: https://github.com/nodejs/node/pull/35922
2368    description: The `fd` option accepts FileHandle arguments.
2369  - version: v14.0.0
2370    pr-url: https://github.com/nodejs/node/pull/31408
2371    description: Change `emitClose` default to `true`.
2372  - version:
2373     - v13.6.0
2374     - v12.17.0
2375    pr-url: https://github.com/nodejs/node/pull/29083
2376    description: The `fs` options allow overriding the used `fs`
2377                 implementation.
2378  - version: v12.10.0
2379    pr-url: https://github.com/nodejs/node/pull/29212
2380    description: Enable `emitClose` option.
2381  - version: v11.0.0
2382    pr-url: https://github.com/nodejs/node/pull/19898
2383    description: Impose new restrictions on `start` and `end`, throwing
2384                 more appropriate errors in cases when we cannot reasonably
2385                 handle the input values.
2386  - version: v7.6.0
2387    pr-url: https://github.com/nodejs/node/pull/10739
2388    description: The `path` parameter can be a WHATWG `URL` object using
2389                 `file:` protocol.
2390  - version: v7.0.0
2391    pr-url: https://github.com/nodejs/node/pull/7831
2392    description: The passed `options` object will never be modified.
2393  - version: v2.3.0
2394    pr-url: https://github.com/nodejs/node/pull/1845
2395    description: The passed `options` object can be a string now.
2396-->
2397
2398* `path` {string|Buffer|URL}
2399* `options` {string|Object}
2400  * `flags` {string} See [support of file system `flags`][]. **Default:**
2401    `'r'`.
2402  * `encoding` {string} **Default:** `null`
2403  * `fd` {integer|FileHandle} **Default:** `null`
2404  * `mode` {integer} **Default:** `0o666`
2405  * `autoClose` {boolean} **Default:** `true`
2406  * `emitClose` {boolean} **Default:** `true`
2407  * `start` {integer}
2408  * `end` {integer} **Default:** `Infinity`
2409  * `highWaterMark` {integer} **Default:** `64 * 1024`
2410  * `fs` {Object|null} **Default:** `null`
2411  * `signal` {AbortSignal|null} **Default:** `null`
2412* Returns: {fs.ReadStream}
2413
2414Unlike the 16 KiB default `highWaterMark` for a {stream.Readable}, the stream
2415returned by this method has a default `highWaterMark` of 64 KiB.
2416
2417`options` can include `start` and `end` values to read a range of bytes from
2418the file instead of the entire file. Both `start` and `end` are inclusive and
2419start counting at 0, allowed values are in the
2420\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `fd` is specified and `start` is
2421omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
2422current file position. The `encoding` can be any one of those accepted by
2423{Buffer}.
2424
2425If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
2426the specified file descriptor. This means that no `'open'` event will be
2427emitted. `fd` should be blocking; non-blocking `fd`s should be passed to
2428{net.Socket}.
2429
2430If `fd` points to a character device that only supports blocking reads
2431(such as keyboard or sound card), read operations do not finish until data is
2432available. This can prevent the process from exiting and the stream from
2433closing naturally.
2434
2435By default, the stream will emit a `'close'` event after it has been
2436destroyed.  Set the `emitClose` option to `false` to change this behavior.
2437
2438By providing the `fs` option, it is possible to override the corresponding `fs`
2439implementations for `open`, `read`, and `close`. When providing the `fs` option,
2440an override for `read` is required. If no `fd` is provided, an override for
2441`open` is also required. If `autoClose` is `true`, an override for `close` is
2442also required.
2443
2444```mjs
2445import { createReadStream } from 'node:fs';
2446
2447// Create a stream from some character device.
2448const stream = createReadStream('/dev/input/event0');
2449setTimeout(() => {
2450  stream.close(); // This may not close the stream.
2451  // Artificially marking end-of-stream, as if the underlying resource had
2452  // indicated end-of-file by itself, allows the stream to close.
2453  // This does not cancel pending read operations, and if there is such an
2454  // operation, the process may still not be able to exit successfully
2455  // until it finishes.
2456  stream.push(null);
2457  stream.read(0);
2458}, 100);
2459```
2460
2461If `autoClose` is false, then the file descriptor won't be closed, even if
2462there's an error. It is the application's responsibility to close it and make
2463sure there's no file descriptor leak. If `autoClose` is set to true (default
2464behavior), on `'error'` or `'end'` the file descriptor will be closed
2465automatically.
2466
2467`mode` sets the file mode (permission and sticky bits), but only if the
2468file was created.
2469
2470An example to read the last 10 bytes of a file which is 100 bytes long:
2471
2472```mjs
2473import { createReadStream } from 'node:fs';
2474
2475createReadStream('sample.txt', { start: 90, end: 99 });
2476```
2477
2478If `options` is a string, then it specifies the encoding.
2479
2480### `fs.createWriteStream(path[, options])`
2481
2482<!-- YAML
2483added: v0.1.31
2484changes:
2485  - version: v16.10.0
2486    pr-url: https://github.com/nodejs/node/pull/40013
2487    description: The `fs` option does not need `open` method if an `fd` was provided.
2488  - version: v16.10.0
2489    pr-url: https://github.com/nodejs/node/pull/40013
2490    description: The `fs` option does not need `close` method if `autoClose` is `false`.
2491  - version: v15.5.0
2492    pr-url: https://github.com/nodejs/node/pull/36431
2493    description: Add support for `AbortSignal`.
2494  - version:
2495     - v15.4.0
2496    pr-url: https://github.com/nodejs/node/pull/35922
2497    description: The `fd` option accepts FileHandle arguments.
2498  - version: v14.0.0
2499    pr-url: https://github.com/nodejs/node/pull/31408
2500    description: Change `emitClose` default to `true`.
2501  - version:
2502     - v13.6.0
2503     - v12.17.0
2504    pr-url: https://github.com/nodejs/node/pull/29083
2505    description: The `fs` options allow overriding the used `fs`
2506                 implementation.
2507  - version: v12.10.0
2508    pr-url: https://github.com/nodejs/node/pull/29212
2509    description: Enable `emitClose` option.
2510  - version: v7.6.0
2511    pr-url: https://github.com/nodejs/node/pull/10739
2512    description: The `path` parameter can be a WHATWG `URL` object using
2513                 `file:` protocol.
2514  - version: v7.0.0
2515    pr-url: https://github.com/nodejs/node/pull/7831
2516    description: The passed `options` object will never be modified.
2517  - version: v5.5.0
2518    pr-url: https://github.com/nodejs/node/pull/3679
2519    description: The `autoClose` option is supported now.
2520  - version: v2.3.0
2521    pr-url: https://github.com/nodejs/node/pull/1845
2522    description: The passed `options` object can be a string now.
2523-->
2524
2525* `path` {string|Buffer|URL}
2526* `options` {string|Object}
2527  * `flags` {string} See [support of file system `flags`][]. **Default:**
2528    `'w'`.
2529  * `encoding` {string} **Default:** `'utf8'`
2530  * `fd` {integer|FileHandle} **Default:** `null`
2531  * `mode` {integer} **Default:** `0o666`
2532  * `autoClose` {boolean} **Default:** `true`
2533  * `emitClose` {boolean} **Default:** `true`
2534  * `start` {integer}
2535  * `fs` {Object|null} **Default:** `null`
2536  * `signal` {AbortSignal|null} **Default:** `null`
2537* Returns: {fs.WriteStream}
2538
2539`options` may also include a `start` option to allow writing data at some
2540position past the beginning of the file, allowed values are in the
2541\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than
2542replacing it may require the `flags` option to be set to `r+` rather than the
2543default `w`. The `encoding` can be any one of those accepted by {Buffer}.
2544
2545If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
2546the file descriptor will be closed automatically. If `autoClose` is false,
2547then the file descriptor won't be closed, even if there's an error.
2548It is the application's responsibility to close it and make sure there's no
2549file descriptor leak.
2550
2551By default, the stream will emit a `'close'` event after it has been
2552destroyed.  Set the `emitClose` option to `false` to change this behavior.
2553
2554By providing the `fs` option it is possible to override the corresponding `fs`
2555implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`
2556without `writev()` can reduce performance as some optimizations (`_writev()`)
2557will be disabled. When providing the `fs` option, overrides for at least one of
2558`write` and `writev` are required. If no `fd` option is supplied, an override
2559for `open` is also required. If `autoClose` is `true`, an override for `close`
2560is also required.
2561
2562Like {fs.ReadStream}, if `fd` is specified, {fs.WriteStream} will ignore the
2563`path` argument and will use the specified file descriptor. This means that no
2564`'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s
2565should be passed to {net.Socket}.
2566
2567If `options` is a string, then it specifies the encoding.
2568
2569### `fs.exists(path, callback)`
2570
2571<!-- YAML
2572added: v0.0.2
2573deprecated: v1.0.0
2574changes:
2575  - version: v18.0.0
2576    pr-url: https://github.com/nodejs/node/pull/41678
2577    description: Passing an invalid callback to the `callback` argument
2578                 now throws `ERR_INVALID_ARG_TYPE` instead of
2579                 `ERR_INVALID_CALLBACK`.
2580  - version: v7.6.0
2581    pr-url: https://github.com/nodejs/node/pull/10739
2582    description: The `path` parameter can be a WHATWG `URL` object using
2583                 `file:` protocol.
2584-->
2585
2586> Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
2587
2588* `path` {string|Buffer|URL}
2589* `callback` {Function}
2590  * `exists` {boolean}
2591
2592Test whether or not the given path exists by checking with the file system.
2593Then call the `callback` argument with either true or false:
2594
2595```mjs
2596import { exists } from 'node:fs';
2597
2598exists('/etc/passwd', (e) => {
2599  console.log(e ? 'it exists' : 'no passwd!');
2600});
2601```
2602
2603**The parameters for this callback are not consistent with other Node.js
2604callbacks.** Normally, the first parameter to a Node.js callback is an `err`
2605parameter, optionally followed by other parameters. The `fs.exists()` callback
2606has only one boolean parameter. This is one reason `fs.access()` is recommended
2607instead of `fs.exists()`.
2608
2609Using `fs.exists()` to check for the existence of a file before calling
2610`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing
2611so introduces a race condition, since other processes may change the file's
2612state between the two calls. Instead, user code should open/read/write the
2613file directly and handle the error raised if the file does not exist.
2614
2615**write (NOT RECOMMENDED)**
2616
2617```mjs
2618import { exists, open, close } from 'node:fs';
2619
2620exists('myfile', (e) => {
2621  if (e) {
2622    console.error('myfile already exists');
2623  } else {
2624    open('myfile', 'wx', (err, fd) => {
2625      if (err) throw err;
2626
2627      try {
2628        writeMyData(fd);
2629      } finally {
2630        close(fd, (err) => {
2631          if (err) throw err;
2632        });
2633      }
2634    });
2635  }
2636});
2637```
2638
2639**write (RECOMMENDED)**
2640
2641```mjs
2642import { open, close } from 'node:fs';
2643open('myfile', 'wx', (err, fd) => {
2644  if (err) {
2645    if (err.code === 'EEXIST') {
2646      console.error('myfile already exists');
2647      return;
2648    }
2649
2650    throw err;
2651  }
2652
2653  try {
2654    writeMyData(fd);
2655  } finally {
2656    close(fd, (err) => {
2657      if (err) throw err;
2658    });
2659  }
2660});
2661```
2662
2663**read (NOT RECOMMENDED)**
2664
2665```mjs
2666import { open, close, exists } from 'node:fs';
2667
2668exists('myfile', (e) => {
2669  if (e) {
2670    open('myfile', 'r', (err, fd) => {
2671      if (err) throw err;
2672
2673      try {
2674        readMyData(fd);
2675      } finally {
2676        close(fd, (err) => {
2677          if (err) throw err;
2678        });
2679      }
2680    });
2681  } else {
2682    console.error('myfile does not exist');
2683  }
2684});
2685```
2686
2687**read (RECOMMENDED)**
2688
2689```mjs
2690import { open, close } from 'node:fs';
2691
2692open('myfile', 'r', (err, fd) => {
2693  if (err) {
2694    if (err.code === 'ENOENT') {
2695      console.error('myfile does not exist');
2696      return;
2697    }
2698
2699    throw err;
2700  }
2701
2702  try {
2703    readMyData(fd);
2704  } finally {
2705    close(fd, (err) => {
2706      if (err) throw err;
2707    });
2708  }
2709});
2710```
2711
2712The "not recommended" examples above check for existence and then use the
2713file; the "recommended" examples are better because they use the file directly
2714and handle the error, if any.
2715
2716In general, check for the existence of a file only if the file won't be
2717used directly, for example when its existence is a signal from another
2718process.
2719
2720### `fs.fchmod(fd, mode, callback)`
2721
2722<!-- YAML
2723added: v0.4.7
2724changes:
2725  - version: v18.0.0
2726    pr-url: https://github.com/nodejs/node/pull/41678
2727    description: Passing an invalid callback to the `callback` argument
2728                 now throws `ERR_INVALID_ARG_TYPE` instead of
2729                 `ERR_INVALID_CALLBACK`.
2730  - version: v10.0.0
2731    pr-url: https://github.com/nodejs/node/pull/12562
2732    description: The `callback` parameter is no longer optional. Not passing
2733                 it will throw a `TypeError` at runtime.
2734  - version: v7.0.0
2735    pr-url: https://github.com/nodejs/node/pull/7897
2736    description: The `callback` parameter is no longer optional. Not passing
2737                 it will emit a deprecation warning with id DEP0013.
2738-->
2739
2740* `fd` {integer}
2741* `mode` {string|integer}
2742* `callback` {Function}
2743  * `err` {Error}
2744
2745Sets the permissions on the file. No arguments other than a possible exception
2746are given to the completion callback.
2747
2748See the POSIX fchmod(2) documentation for more detail.
2749
2750### `fs.fchown(fd, uid, gid, callback)`
2751
2752<!-- YAML
2753added: v0.4.7
2754changes:
2755  - version: v18.0.0
2756    pr-url: https://github.com/nodejs/node/pull/41678
2757    description: Passing an invalid callback to the `callback` argument
2758                 now throws `ERR_INVALID_ARG_TYPE` instead of
2759                 `ERR_INVALID_CALLBACK`.
2760  - version: v10.0.0
2761    pr-url: https://github.com/nodejs/node/pull/12562
2762    description: The `callback` parameter is no longer optional. Not passing
2763                 it will throw a `TypeError` at runtime.
2764  - version: v7.0.0
2765    pr-url: https://github.com/nodejs/node/pull/7897
2766    description: The `callback` parameter is no longer optional. Not passing
2767                 it will emit a deprecation warning with id DEP0013.
2768-->
2769
2770* `fd` {integer}
2771* `uid` {integer}
2772* `gid` {integer}
2773* `callback` {Function}
2774  * `err` {Error}
2775
2776Sets the owner of the file. No arguments other than a possible exception are
2777given to the completion callback.
2778
2779See the POSIX fchown(2) documentation for more detail.
2780
2781### `fs.fdatasync(fd, callback)`
2782
2783<!-- YAML
2784added: v0.1.96
2785changes:
2786  - version: v18.0.0
2787    pr-url: https://github.com/nodejs/node/pull/41678
2788    description: Passing an invalid callback to the `callback` argument
2789                 now throws `ERR_INVALID_ARG_TYPE` instead of
2790                 `ERR_INVALID_CALLBACK`.
2791  - version: v10.0.0
2792    pr-url: https://github.com/nodejs/node/pull/12562
2793    description: The `callback` parameter is no longer optional. Not passing
2794                 it will throw a `TypeError` at runtime.
2795  - version: v7.0.0
2796    pr-url: https://github.com/nodejs/node/pull/7897
2797    description: The `callback` parameter is no longer optional. Not passing
2798                 it will emit a deprecation warning with id DEP0013.
2799-->
2800
2801* `fd` {integer}
2802* `callback` {Function}
2803  * `err` {Error}
2804
2805Forces all currently queued I/O operations associated with the file to the
2806operating system's synchronized I/O completion state. Refer to the POSIX
2807fdatasync(2) documentation for details. No arguments other than a possible
2808exception are given to the completion callback.
2809
2810### `fs.fstat(fd[, options], callback)`
2811
2812<!-- YAML
2813added: v0.1.95
2814changes:
2815  - version: v18.0.0
2816    pr-url: https://github.com/nodejs/node/pull/41678
2817    description: Passing an invalid callback to the `callback` argument
2818                 now throws `ERR_INVALID_ARG_TYPE` instead of
2819                 `ERR_INVALID_CALLBACK`.
2820  - version: v10.5.0
2821    pr-url: https://github.com/nodejs/node/pull/20220
2822    description: Accepts an additional `options` object to specify whether
2823                 the numeric values returned should be bigint.
2824  - version: v10.0.0
2825    pr-url: https://github.com/nodejs/node/pull/12562
2826    description: The `callback` parameter is no longer optional. Not passing
2827                 it will throw a `TypeError` at runtime.
2828  - version: v7.0.0
2829    pr-url: https://github.com/nodejs/node/pull/7897
2830    description: The `callback` parameter is no longer optional. Not passing
2831                 it will emit a deprecation warning with id DEP0013.
2832-->
2833
2834* `fd` {integer}
2835* `options` {Object}
2836  * `bigint` {boolean} Whether the numeric values in the returned
2837    {fs.Stats} object should be `bigint`. **Default:** `false`.
2838* `callback` {Function}
2839  * `err` {Error}
2840  * `stats` {fs.Stats}
2841
2842Invokes the callback with the {fs.Stats} for the file descriptor.
2843
2844See the POSIX fstat(2) documentation for more detail.
2845
2846### `fs.fsync(fd, callback)`
2847
2848<!-- YAML
2849added: v0.1.96
2850changes:
2851  - version: v18.0.0
2852    pr-url: https://github.com/nodejs/node/pull/41678
2853    description: Passing an invalid callback to the `callback` argument
2854                 now throws `ERR_INVALID_ARG_TYPE` instead of
2855                 `ERR_INVALID_CALLBACK`.
2856  - version: v10.0.0
2857    pr-url: https://github.com/nodejs/node/pull/12562
2858    description: The `callback` parameter is no longer optional. Not passing
2859                 it will throw a `TypeError` at runtime.
2860  - version: v7.0.0
2861    pr-url: https://github.com/nodejs/node/pull/7897
2862    description: The `callback` parameter is no longer optional. Not passing
2863                 it will emit a deprecation warning with id DEP0013.
2864-->
2865
2866* `fd` {integer}
2867* `callback` {Function}
2868  * `err` {Error}
2869
2870Request that all data for the open file descriptor is flushed to the storage
2871device. The specific implementation is operating system and device specific.
2872Refer to the POSIX fsync(2) documentation for more detail. No arguments other
2873than a possible exception are given to the completion callback.
2874
2875### `fs.ftruncate(fd[, len], callback)`
2876
2877<!-- YAML
2878added: v0.8.6
2879changes:
2880  - version: v18.0.0
2881    pr-url: https://github.com/nodejs/node/pull/41678
2882    description: Passing an invalid callback to the `callback` argument
2883                 now throws `ERR_INVALID_ARG_TYPE` instead of
2884                 `ERR_INVALID_CALLBACK`.
2885  - version: v10.0.0
2886    pr-url: https://github.com/nodejs/node/pull/12562
2887    description: The `callback` parameter is no longer optional. Not passing
2888                 it will throw a `TypeError` at runtime.
2889  - version: v7.0.0
2890    pr-url: https://github.com/nodejs/node/pull/7897
2891    description: The `callback` parameter is no longer optional. Not passing
2892                 it will emit a deprecation warning with id DEP0013.
2893-->
2894
2895* `fd` {integer}
2896* `len` {integer} **Default:** `0`
2897* `callback` {Function}
2898  * `err` {Error}
2899
2900Truncates the file descriptor. No arguments other than a possible exception are
2901given to the completion callback.
2902
2903See the POSIX ftruncate(2) documentation for more detail.
2904
2905If the file referred to by the file descriptor was larger than `len` bytes, only
2906the first `len` bytes will be retained in the file.
2907
2908For example, the following program retains only the first four bytes of the
2909file:
2910
2911```mjs
2912import { open, close, ftruncate } from 'node:fs';
2913
2914function closeFd(fd) {
2915  close(fd, (err) => {
2916    if (err) throw err;
2917  });
2918}
2919
2920open('temp.txt', 'r+', (err, fd) => {
2921  if (err) throw err;
2922
2923  try {
2924    ftruncate(fd, 4, (err) => {
2925      closeFd(fd);
2926      if (err) throw err;
2927    });
2928  } catch (err) {
2929    closeFd(fd);
2930    if (err) throw err;
2931  }
2932});
2933```
2934
2935If the file previously was shorter than `len` bytes, it is extended, and the
2936extended part is filled with null bytes (`'\0'`):
2937
2938If `len` is negative then `0` will be used.
2939
2940### `fs.futimes(fd, atime, mtime, callback)`
2941
2942<!-- YAML
2943added: v0.4.2
2944changes:
2945  - version: v18.0.0
2946    pr-url: https://github.com/nodejs/node/pull/41678
2947    description: Passing an invalid callback to the `callback` argument
2948                 now throws `ERR_INVALID_ARG_TYPE` instead of
2949                 `ERR_INVALID_CALLBACK`.
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.0.0
2955    pr-url: https://github.com/nodejs/node/pull/7897
2956    description: The `callback` parameter is no longer optional. Not passing
2957                 it will emit a deprecation warning with id DEP0013.
2958  - version: v4.1.0
2959    pr-url: https://github.com/nodejs/node/pull/2387
2960    description: Numeric strings, `NaN`, and `Infinity` are now allowed
2961                 time specifiers.
2962-->
2963
2964* `fd` {integer}
2965* `atime` {number|string|Date}
2966* `mtime` {number|string|Date}
2967* `callback` {Function}
2968  * `err` {Error}
2969
2970Change the file system timestamps of the object referenced by the supplied file
2971descriptor. See [`fs.utimes()`][].
2972
2973### `fs.lchmod(path, mode, callback)`
2974
2975<!-- YAML
2976deprecated: v0.4.7
2977changes:
2978  - version: v18.0.0
2979    pr-url: https://github.com/nodejs/node/pull/41678
2980    description: Passing an invalid callback to the `callback` argument
2981                 now throws `ERR_INVALID_ARG_TYPE` instead of
2982                 `ERR_INVALID_CALLBACK`.
2983  - version: v16.0.0
2984    pr-url: https://github.com/nodejs/node/pull/37460
2985    description: The error returned may be an `AggregateError` if more than one
2986                 error is returned.
2987  - version: v10.0.0
2988    pr-url: https://github.com/nodejs/node/pull/12562
2989    description: The `callback` parameter is no longer optional. Not passing
2990                 it will throw a `TypeError` at runtime.
2991  - version: v7.0.0
2992    pr-url: https://github.com/nodejs/node/pull/7897
2993    description: The `callback` parameter is no longer optional. Not passing
2994                 it will emit a deprecation warning with id DEP0013.
2995-->
2996
2997* `path` {string|Buffer|URL}
2998* `mode` {integer}
2999* `callback` {Function}
3000  * `err` {Error|AggregateError}
3001
3002Changes the permissions on a symbolic link. No arguments other than a possible
3003exception are given to the completion callback.
3004
3005This method is only implemented on macOS.
3006
3007See the POSIX lchmod(2) documentation for more detail.
3008
3009### `fs.lchown(path, uid, gid, callback)`
3010
3011<!-- YAML
3012changes:
3013  - version: v18.0.0
3014    pr-url: https://github.com/nodejs/node/pull/41678
3015    description: Passing an invalid callback to the `callback` argument
3016                 now throws `ERR_INVALID_ARG_TYPE` instead of
3017                 `ERR_INVALID_CALLBACK`.
3018  - version: v10.6.0
3019    pr-url: https://github.com/nodejs/node/pull/21498
3020    description: This API is no longer deprecated.
3021  - version: v10.0.0
3022    pr-url: https://github.com/nodejs/node/pull/12562
3023    description: The `callback` parameter is no longer optional. Not passing
3024                 it will throw a `TypeError` at runtime.
3025  - version: v7.0.0
3026    pr-url: https://github.com/nodejs/node/pull/7897
3027    description: The `callback` parameter is no longer optional. Not passing
3028                 it will emit a deprecation warning with id DEP0013.
3029  - version: v0.4.7
3030    description: Documentation-only deprecation.
3031-->
3032
3033* `path` {string|Buffer|URL}
3034* `uid` {integer}
3035* `gid` {integer}
3036* `callback` {Function}
3037  * `err` {Error}
3038
3039Set the owner of the symbolic link. No arguments other than a possible
3040exception are given to the completion callback.
3041
3042See the POSIX lchown(2) documentation for more detail.
3043
3044### `fs.lutimes(path, atime, mtime, callback)`
3045
3046<!-- YAML
3047added:
3048  - v14.5.0
3049  - v12.19.0
3050changes:
3051  - version: v18.0.0
3052    pr-url: https://github.com/nodejs/node/pull/41678
3053    description: Passing an invalid callback to the `callback` argument
3054                 now throws `ERR_INVALID_ARG_TYPE` instead of
3055                 `ERR_INVALID_CALLBACK`.
3056-->
3057
3058* `path` {string|Buffer|URL}
3059* `atime` {number|string|Date}
3060* `mtime` {number|string|Date}
3061* `callback` {Function}
3062  * `err` {Error}
3063
3064Changes the access and modification times of a file in the same way as
3065[`fs.utimes()`][], with the difference that if the path refers to a symbolic
3066link, then the link is not dereferenced: instead, the timestamps of the
3067symbolic link itself are changed.
3068
3069No arguments other than a possible exception are given to the completion
3070callback.
3071
3072### `fs.link(existingPath, newPath, callback)`
3073
3074<!-- YAML
3075added: v0.1.31
3076changes:
3077  - version: v18.0.0
3078    pr-url: https://github.com/nodejs/node/pull/41678
3079    description: Passing an invalid callback to the `callback` argument
3080                 now throws `ERR_INVALID_ARG_TYPE` instead of
3081                 `ERR_INVALID_CALLBACK`.
3082  - version: v10.0.0
3083    pr-url: https://github.com/nodejs/node/pull/12562
3084    description: The `callback` parameter is no longer optional. Not passing
3085                 it will throw a `TypeError` at runtime.
3086  - version: v7.6.0
3087    pr-url: https://github.com/nodejs/node/pull/10739
3088    description: The `existingPath` and `newPath` parameters can be WHATWG
3089                 `URL` objects using `file:` protocol. Support is currently
3090                 still *experimental*.
3091  - version: v7.0.0
3092    pr-url: https://github.com/nodejs/node/pull/7897
3093    description: The `callback` parameter is no longer optional. Not passing
3094                 it will emit a deprecation warning with id DEP0013.
3095-->
3096
3097* `existingPath` {string|Buffer|URL}
3098* `newPath` {string|Buffer|URL}
3099* `callback` {Function}
3100  * `err` {Error}
3101
3102Creates a new link from the `existingPath` to the `newPath`. See the POSIX
3103link(2) documentation for more detail. No arguments other than a possible
3104exception are given to the completion callback.
3105
3106### `fs.lstat(path[, options], callback)`
3107
3108<!-- YAML
3109added: v0.1.30
3110changes:
3111  - version: v18.0.0
3112    pr-url: https://github.com/nodejs/node/pull/41678
3113    description: Passing an invalid callback to the `callback` argument
3114                 now throws `ERR_INVALID_ARG_TYPE` instead of
3115                 `ERR_INVALID_CALLBACK`.
3116  - version: v10.5.0
3117    pr-url: https://github.com/nodejs/node/pull/20220
3118    description: Accepts an additional `options` object to specify whether
3119                 the numeric values returned should be bigint.
3120  - version: v10.0.0
3121    pr-url: https://github.com/nodejs/node/pull/12562
3122    description: The `callback` parameter is no longer optional. Not passing
3123                 it will throw a `TypeError` at runtime.
3124  - version: v7.6.0
3125    pr-url: https://github.com/nodejs/node/pull/10739
3126    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3127                 protocol.
3128  - version: v7.0.0
3129    pr-url: https://github.com/nodejs/node/pull/7897
3130    description: The `callback` parameter is no longer optional. Not passing
3131                 it will emit a deprecation warning with id DEP0013.
3132-->
3133
3134* `path` {string|Buffer|URL}
3135* `options` {Object}
3136  * `bigint` {boolean} Whether the numeric values in the returned
3137    {fs.Stats} object should be `bigint`. **Default:** `false`.
3138* `callback` {Function}
3139  * `err` {Error}
3140  * `stats` {fs.Stats}
3141
3142Retrieves the {fs.Stats} for the symbolic link referred to by the path.
3143The callback gets two arguments `(err, stats)` where `stats` is a {fs.Stats}
3144object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic
3145link, then the link itself is stat-ed, not the file that it refers to.
3146
3147See the POSIX lstat(2) documentation for more details.
3148
3149### `fs.mkdir(path[, options], callback)`
3150
3151<!-- YAML
3152added: v0.1.8
3153changes:
3154  - version: v18.0.0
3155    pr-url: https://github.com/nodejs/node/pull/41678
3156    description: Passing an invalid callback to the `callback` argument
3157                 now throws `ERR_INVALID_ARG_TYPE` instead of
3158                 `ERR_INVALID_CALLBACK`.
3159  - version:
3160     - v13.11.0
3161     - v12.17.0
3162    pr-url: https://github.com/nodejs/node/pull/31530
3163    description: In `recursive` mode, the callback now receives the first
3164                 created path as an argument.
3165  - version: v10.12.0
3166    pr-url: https://github.com/nodejs/node/pull/21875
3167    description: The second argument can now be an `options` object with
3168                 `recursive` and `mode` properties.
3169  - version: v10.0.0
3170    pr-url: https://github.com/nodejs/node/pull/12562
3171    description: The `callback` parameter is no longer optional. Not passing
3172                 it will throw a `TypeError` at runtime.
3173  - version: v7.6.0
3174    pr-url: https://github.com/nodejs/node/pull/10739
3175    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3176                 protocol.
3177  - version: v7.0.0
3178    pr-url: https://github.com/nodejs/node/pull/7897
3179    description: The `callback` parameter is no longer optional. Not passing
3180                 it will emit a deprecation warning with id DEP0013.
3181-->
3182
3183* `path` {string|Buffer|URL}
3184* `options` {Object|integer}
3185  * `recursive` {boolean} **Default:** `false`
3186  * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
3187* `callback` {Function}
3188  * `err` {Error}
3189  * `path` {string|undefined} Present only if a directory is created with
3190    `recursive` set to `true`.
3191
3192Asynchronously creates a directory.
3193
3194The callback is given a possible exception and, if `recursive` is `true`, the
3195first directory path created, `(err[, path])`.
3196`path` can still be `undefined` when `recursive` is `true`, if no directory was
3197created (for instance, if it was previously created).
3198
3199The optional `options` argument can be an integer specifying `mode` (permission
3200and sticky bits), or an object with a `mode` property and a `recursive`
3201property indicating whether parent directories should be created. Calling
3202`fs.mkdir()` when `path` is a directory that exists results in an error only
3203when `recursive` is false. If `recursive` is false and the directory exists,
3204an `EEXIST` error occurs.
3205
3206```mjs
3207import { mkdir } from 'node:fs';
3208
3209// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
3210mkdir('./tmp/a/apple', { recursive: true }, (err) => {
3211  if (err) throw err;
3212});
3213```
3214
3215On Windows, using `fs.mkdir()` on the root directory even with recursion will
3216result in an error:
3217
3218```mjs
3219import { mkdir } from 'node:fs';
3220
3221mkdir('/', { recursive: true }, (err) => {
3222  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
3223});
3224```
3225
3226See the POSIX mkdir(2) documentation for more details.
3227
3228### `fs.mkdtemp(prefix[, options], callback)`
3229
3230<!-- YAML
3231added: v5.10.0
3232changes:
3233  - version: v18.19.0
3234    pr-url: https://github.com/nodejs/node/pull/48828
3235    description: The `prefix` parameter now accepts buffers and URL.
3236  - version: v18.0.0
3237    pr-url: https://github.com/nodejs/node/pull/41678
3238    description: Passing an invalid callback to the `callback` argument
3239                 now throws `ERR_INVALID_ARG_TYPE` instead of
3240                 `ERR_INVALID_CALLBACK`.
3241  - version:
3242      - v16.5.0
3243      - v14.18.0
3244    pr-url: https://github.com/nodejs/node/pull/39028
3245    description: The `prefix` parameter now accepts an empty string.
3246  - version: v10.0.0
3247    pr-url: https://github.com/nodejs/node/pull/12562
3248    description: The `callback` parameter is no longer optional. Not passing
3249                 it will throw a `TypeError` at runtime.
3250  - version: v7.0.0
3251    pr-url: https://github.com/nodejs/node/pull/7897
3252    description: The `callback` parameter is no longer optional. Not passing
3253                 it will emit a deprecation warning with id DEP0013.
3254  - version: v6.2.1
3255    pr-url: https://github.com/nodejs/node/pull/6828
3256    description: The `callback` parameter is optional now.
3257-->
3258
3259* `prefix` {string|Buffer|URL}
3260* `options` {string|Object}
3261  * `encoding` {string} **Default:** `'utf8'`
3262* `callback` {Function}
3263  * `err` {Error}
3264  * `directory` {string}
3265
3266Creates a unique temporary directory.
3267
3268Generates six random characters to be appended behind a required
3269`prefix` to create a unique temporary directory. Due to platform
3270inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
3271notably the BSDs, can return more than six random characters, and replace
3272trailing `X` characters in `prefix` with random characters.
3273
3274The created directory path is passed as a string to the callback's second
3275parameter.
3276
3277The optional `options` argument can be a string specifying an encoding, or an
3278object with an `encoding` property specifying the character encoding to use.
3279
3280```mjs
3281import { mkdtemp } from 'node:fs';
3282import { join } from 'node:path';
3283import { tmpdir } from 'node:os';
3284
3285mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
3286  if (err) throw err;
3287  console.log(directory);
3288  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
3289});
3290```
3291
3292The `fs.mkdtemp()` method will append the six randomly selected characters
3293directly to the `prefix` string. For instance, given a directory `/tmp`, if the
3294intention is to create a temporary directory _within_ `/tmp`, the `prefix`
3295must end with a trailing platform-specific path separator
3296(`require('node:path').sep`).
3297
3298```mjs
3299import { tmpdir } from 'node:os';
3300import { mkdtemp } from 'node:fs';
3301
3302// The parent directory for the new temporary directory
3303const tmpDir = tmpdir();
3304
3305// This method is *INCORRECT*:
3306mkdtemp(tmpDir, (err, directory) => {
3307  if (err) throw err;
3308  console.log(directory);
3309  // Will print something similar to `/tmpabc123`.
3310  // A new temporary directory is created at the file system root
3311  // rather than *within* the /tmp directory.
3312});
3313
3314// This method is *CORRECT*:
3315import { sep } from 'node:path';
3316mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
3317  if (err) throw err;
3318  console.log(directory);
3319  // Will print something similar to `/tmp/abc123`.
3320  // A new temporary directory is created within
3321  // the /tmp directory.
3322});
3323```
3324
3325### `fs.open(path[, flags[, mode]], callback)`
3326
3327<!-- YAML
3328added: v0.0.2
3329changes:
3330  - version: v18.0.0
3331    pr-url: https://github.com/nodejs/node/pull/41678
3332    description: Passing an invalid callback to the `callback` argument
3333                 now throws `ERR_INVALID_ARG_TYPE` instead of
3334                 `ERR_INVALID_CALLBACK`.
3335  - version: v11.1.0
3336    pr-url: https://github.com/nodejs/node/pull/23767
3337    description: The `flags` argument is now optional and defaults to `'r'`.
3338  - version: v9.9.0
3339    pr-url: https://github.com/nodejs/node/pull/18801
3340    description: The `as` and `as+` flags are supported now.
3341  - version: v7.6.0
3342    pr-url: https://github.com/nodejs/node/pull/10739
3343    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3344                 protocol.
3345-->
3346
3347* `path` {string|Buffer|URL}
3348* `flags` {string|number} See [support of file system `flags`][].
3349  **Default:** `'r'`.
3350* `mode` {string|integer} **Default:** `0o666` (readable and writable)
3351* `callback` {Function}
3352  * `err` {Error}
3353  * `fd` {integer}
3354
3355Asynchronous file open. See the POSIX open(2) documentation for more details.
3356
3357`mode` sets the file mode (permission and sticky bits), but only if the file was
3358created. On Windows, only the write permission can be manipulated; see
3359[`fs.chmod()`][].
3360
3361The callback gets two arguments `(err, fd)`.
3362
3363Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
3364by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains
3365a colon, Node.js will open a file system stream, as described by
3366[this MSDN page][MSDN-Using-Streams].
3367
3368Functions based on `fs.open()` exhibit this behavior as well:
3369`fs.writeFile()`, `fs.readFile()`, etc.
3370
3371### `fs.opendir(path[, options], callback)`
3372
3373<!-- YAML
3374added: v12.12.0
3375changes:
3376  - version: v18.17.0
3377    pr-url: https://github.com/nodejs/node/pull/41439
3378    description: Added `recursive` option.
3379  - version: v18.0.0
3380    pr-url: https://github.com/nodejs/node/pull/41678
3381    description: Passing an invalid callback to the `callback` argument
3382                 now throws `ERR_INVALID_ARG_TYPE` instead of
3383                 `ERR_INVALID_CALLBACK`.
3384  - version:
3385     - v13.1.0
3386     - v12.16.0
3387    pr-url: https://github.com/nodejs/node/pull/30114
3388    description: The `bufferSize` option was introduced.
3389-->
3390
3391* `path` {string|Buffer|URL}
3392* `options` {Object}
3393  * `encoding` {string|null} **Default:** `'utf8'`
3394  * `bufferSize` {number} Number of directory entries that are buffered
3395    internally when reading from the directory. Higher values lead to better
3396    performance but higher memory usage. **Default:** `32`
3397  * `recursive` {boolean} **Default:** `false`
3398* `callback` {Function}
3399  * `err` {Error}
3400  * `dir` {fs.Dir}
3401
3402Asynchronously open a directory. See the POSIX opendir(3) documentation for
3403more details.
3404
3405Creates an {fs.Dir}, which contains all further functions for reading from
3406and cleaning up the directory.
3407
3408The `encoding` option sets the encoding for the `path` while opening the
3409directory and subsequent read operations.
3410
3411### `fs.read(fd, buffer, offset, length, position, callback)`
3412
3413<!-- YAML
3414added: v0.0.2
3415changes:
3416  - version: v18.0.0
3417    pr-url: https://github.com/nodejs/node/pull/41678
3418    description: Passing an invalid callback to the `callback` argument
3419                 now throws `ERR_INVALID_ARG_TYPE` instead of
3420                 `ERR_INVALID_CALLBACK`.
3421  - version: v10.10.0
3422    pr-url: https://github.com/nodejs/node/pull/22150
3423    description: The `buffer` parameter can now be any `TypedArray`, or a
3424                 `DataView`.
3425  - version: v7.4.0
3426    pr-url: https://github.com/nodejs/node/pull/10382
3427    description: The `buffer` parameter can now be a `Uint8Array`.
3428  - version: v6.0.0
3429    pr-url: https://github.com/nodejs/node/pull/4518
3430    description: The `length` parameter can now be `0`.
3431-->
3432
3433* `fd` {integer}
3434* `buffer` {Buffer|TypedArray|DataView} The buffer that the data will be
3435  written to.
3436* `offset` {integer} The position in `buffer` to write the data to.
3437* `length` {integer} The number of bytes to read.
3438* `position` {integer|bigint|null} Specifies where to begin reading from in the
3439  file. If `position` is `null` or `-1 `, data will be read from the current
3440  file position, and the file position will be updated. If `position` is an
3441  integer, the file position will be unchanged.
3442* `callback` {Function}
3443  * `err` {Error}
3444  * `bytesRead` {integer}
3445  * `buffer` {Buffer}
3446
3447Read data from the file specified by `fd`.
3448
3449The callback is given the three arguments, `(err, bytesRead, buffer)`.
3450
3451If the file is not modified concurrently, the end-of-file is reached when the
3452number of bytes read is zero.
3453
3454If this method is invoked as its [`util.promisify()`][]ed version, it returns
3455a promise for an `Object` with `bytesRead` and `buffer` properties.
3456
3457### `fs.read(fd[, options], callback)`
3458
3459<!-- YAML
3460added:
3461 - v13.11.0
3462 - v12.17.0
3463changes:
3464  - version:
3465     - v13.11.0
3466     - v12.17.0
3467    pr-url: https://github.com/nodejs/node/pull/31402
3468    description: Options object can be passed in
3469                 to make buffer, offset, length, and position optional.
3470-->
3471
3472* `fd` {integer}
3473* `options` {Object}
3474  * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)`
3475  * `offset` {integer} **Default:** `0`
3476  * `length` {integer} **Default:** `buffer.byteLength - offset`
3477  * `position` {integer|bigint|null} **Default:** `null`
3478* `callback` {Function}
3479  * `err` {Error}
3480  * `bytesRead` {integer}
3481  * `buffer` {Buffer}
3482
3483Similar to the [`fs.read()`][] function, this version takes an optional
3484`options` object. If no `options` object is specified, it will default with the
3485above values.
3486
3487### `fs.read(fd, buffer[, options], callback)`
3488
3489<!-- YAML
3490added: v18.2.0
3491-->
3492
3493* `fd` {integer}
3494* `buffer` {Buffer|TypedArray|DataView} The buffer that the data will be
3495  written to.
3496* `options` {Object}
3497  * `offset` {integer} **Default:** `0`
3498  * `length` {integer} **Default:** `buffer.byteLength - offset`
3499  * `position` {integer|bigint} **Default:** `null`
3500* `callback` {Function}
3501  * `err` {Error}
3502  * `bytesRead` {integer}
3503  * `buffer` {Buffer}
3504
3505Similar to the [`fs.read()`][] function, this version takes an optional
3506`options` object. If no `options` object is specified, it will default with the
3507above values.
3508
3509### `fs.readdir(path[, options], callback)`
3510
3511<!-- YAML
3512added: v0.1.8
3513changes:
3514  - version: v18.17.0
3515    pr-url: https://github.com/nodejs/node/pull/41439
3516    description: Added `recursive` option.
3517  - version: v18.0.0
3518    pr-url: https://github.com/nodejs/node/pull/41678
3519    description: Passing an invalid callback to the `callback` argument
3520                 now throws `ERR_INVALID_ARG_TYPE` instead of
3521                 `ERR_INVALID_CALLBACK`.
3522  - version: v10.10.0
3523    pr-url: https://github.com/nodejs/node/pull/22020
3524    description: New option `withFileTypes` was added.
3525  - version: v10.0.0
3526    pr-url: https://github.com/nodejs/node/pull/12562
3527    description: The `callback` parameter is no longer optional. Not passing
3528                 it will throw a `TypeError` at runtime.
3529  - version: v7.6.0
3530    pr-url: https://github.com/nodejs/node/pull/10739
3531    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3532                 protocol.
3533  - version: v7.0.0
3534    pr-url: https://github.com/nodejs/node/pull/7897
3535    description: The `callback` parameter is no longer optional. Not passing
3536                 it will emit a deprecation warning with id DEP0013.
3537  - version: v6.0.0
3538    pr-url: https://github.com/nodejs/node/pull/5616
3539    description: The `options` parameter was added.
3540-->
3541
3542* `path` {string|Buffer|URL}
3543* `options` {string|Object}
3544  * `encoding` {string} **Default:** `'utf8'`
3545  * `withFileTypes` {boolean} **Default:** `false`
3546  * `recursive` {boolean} **Default:** `false`
3547* `callback` {Function}
3548  * `err` {Error}
3549  * `files` {string\[]|Buffer\[]|fs.Dirent\[]}
3550
3551Reads the contents of a directory. The callback gets two arguments `(err, files)`
3552where `files` is an array of the names of the files in the directory excluding
3553`'.'` and `'..'`.
3554
3555See the POSIX readdir(3) documentation for more details.
3556
3557The optional `options` argument can be a string specifying an encoding, or an
3558object with an `encoding` property specifying the character encoding to use for
3559the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
3560the filenames returned will be passed as {Buffer} objects.
3561
3562If `options.withFileTypes` is set to `true`, the `files` array will contain
3563{fs.Dirent} objects.
3564
3565### `fs.readFile(path[, options], callback)`
3566
3567<!-- YAML
3568added: v0.1.29
3569changes:
3570  - version: v18.0.0
3571    pr-url: https://github.com/nodejs/node/pull/41678
3572    description: Passing an invalid callback to the `callback` argument
3573                 now throws `ERR_INVALID_ARG_TYPE` instead of
3574                 `ERR_INVALID_CALLBACK`.
3575  - version: v16.0.0
3576    pr-url: https://github.com/nodejs/node/pull/37460
3577    description: The error returned may be an `AggregateError` if more than one
3578                 error is returned.
3579  - version:
3580      - v15.2.0
3581      - v14.17.0
3582    pr-url: https://github.com/nodejs/node/pull/35911
3583    description: The options argument may include an AbortSignal to abort an
3584                 ongoing readFile request.
3585  - version: v10.0.0
3586    pr-url: https://github.com/nodejs/node/pull/12562
3587    description: The `callback` parameter is no longer optional. Not passing
3588                 it will throw a `TypeError` at runtime.
3589  - version: v7.6.0
3590    pr-url: https://github.com/nodejs/node/pull/10739
3591    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3592                 protocol.
3593  - version: v7.0.0
3594    pr-url: https://github.com/nodejs/node/pull/7897
3595    description: The `callback` parameter is no longer optional. Not passing
3596                 it will emit a deprecation warning with id DEP0013.
3597  - version: v5.1.0
3598    pr-url: https://github.com/nodejs/node/pull/3740
3599    description: The `callback` will always be called with `null` as the `error`
3600                 parameter in case of success.
3601  - version: v5.0.0
3602    pr-url: https://github.com/nodejs/node/pull/3163
3603    description: The `path` parameter can be a file descriptor now.
3604-->
3605
3606* `path` {string|Buffer|URL|integer} filename or file descriptor
3607* `options` {Object|string}
3608  * `encoding` {string|null} **Default:** `null`
3609  * `flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.
3610  * `signal` {AbortSignal} allows aborting an in-progress readFile
3611* `callback` {Function}
3612  * `err` {Error|AggregateError}
3613  * `data` {string|Buffer}
3614
3615Asynchronously reads the entire contents of a file.
3616
3617```mjs
3618import { readFile } from 'node:fs';
3619
3620readFile('/etc/passwd', (err, data) => {
3621  if (err) throw err;
3622  console.log(data);
3623});
3624```
3625
3626The callback is passed two arguments `(err, data)`, where `data` is the
3627contents of the file.
3628
3629If no encoding is specified, then the raw buffer is returned.
3630
3631If `options` is a string, then it specifies the encoding:
3632
3633```mjs
3634import { readFile } from 'node:fs';
3635
3636readFile('/etc/passwd', 'utf8', callback);
3637```
3638
3639When the path is a directory, the behavior of `fs.readFile()` and
3640[`fs.readFileSync()`][] is platform-specific. On macOS, Linux, and Windows, an
3641error will be returned. On FreeBSD, a representation of the directory's contents
3642will be returned.
3643
3644```mjs
3645import { readFile } from 'node:fs';
3646
3647// macOS, Linux, and Windows
3648readFile('<directory>', (err, data) => {
3649  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
3650});
3651
3652//  FreeBSD
3653readFile('<directory>', (err, data) => {
3654  // => null, <data>
3655});
3656```
3657
3658It is possible to abort an ongoing request using an `AbortSignal`. If a
3659request is aborted the callback is called with an `AbortError`:
3660
3661```mjs
3662import { readFile } from 'node:fs';
3663
3664const controller = new AbortController();
3665const signal = controller.signal;
3666readFile(fileInfo[0].name, { signal }, (err, buf) => {
3667  // ...
3668});
3669// When you want to abort the request
3670controller.abort();
3671```
3672
3673The `fs.readFile()` function buffers the entire file. To minimize memory costs,
3674when possible prefer streaming via `fs.createReadStream()`.
3675
3676Aborting an ongoing request does not abort individual operating
3677system requests but rather the internal buffering `fs.readFile` performs.
3678
3679#### File descriptors
3680
36811. Any specified file descriptor has to support reading.
36822. If a file descriptor is specified as the `path`, it will not be closed
3683   automatically.
36843. The reading will begin at the current position. For example, if the file
3685   already had `'Hello World`' and six bytes are read with the file descriptor,
3686   the call to `fs.readFile()` with the same file descriptor, would give
3687   `'World'`, rather than `'Hello World'`.
3688
3689#### Performance Considerations
3690
3691The `fs.readFile()` method asynchronously reads the contents of a file into
3692memory one chunk at a time, allowing the event loop to turn between each chunk.
3693This allows the read operation to have less impact on other activity that may
3694be using the underlying libuv thread pool but means that it will take longer
3695to read a complete file into memory.
3696
3697The additional read overhead can vary broadly on different systems and depends
3698on the type of file being read. If the file type is not a regular file (a pipe
3699for instance) and Node.js is unable to determine an actual file size, each read
3700operation will load on 64 KiB of data. For regular files, each read will process
3701512 KiB of data.
3702
3703For applications that require as-fast-as-possible reading of file contents, it
3704is better to use `fs.read()` directly and for application code to manage
3705reading the full contents of the file itself.
3706
3707The Node.js GitHub issue [#25741][] provides more information and a detailed
3708analysis on the performance of `fs.readFile()` for multiple file sizes in
3709different Node.js versions.
3710
3711### `fs.readlink(path[, options], callback)`
3712
3713<!-- YAML
3714added: v0.1.31
3715changes:
3716  - version: v18.0.0
3717    pr-url: https://github.com/nodejs/node/pull/41678
3718    description: Passing an invalid callback to the `callback` argument
3719                 now throws `ERR_INVALID_ARG_TYPE` instead of
3720                 `ERR_INVALID_CALLBACK`.
3721  - version: v10.0.0
3722    pr-url: https://github.com/nodejs/node/pull/12562
3723    description: The `callback` parameter is no longer optional. Not passing
3724                 it will throw a `TypeError` at runtime.
3725  - version: v7.6.0
3726    pr-url: https://github.com/nodejs/node/pull/10739
3727    description: The `path` parameter can be a WHATWG `URL` object using `file:`
3728                 protocol.
3729  - version: v7.0.0
3730    pr-url: https://github.com/nodejs/node/pull/7897
3731    description: The `callback` parameter is no longer optional. Not passing
3732                 it will emit a deprecation warning with id DEP0013.
3733-->
3734
3735* `path` {string|Buffer|URL}
3736* `options` {string|Object}
3737  * `encoding` {string} **Default:** `'utf8'`
3738* `callback` {Function}
3739  * `err` {Error}
3740  * `linkString` {string|Buffer}
3741
3742Reads the contents of the symbolic link referred to by `path`. The callback gets
3743two arguments `(err, linkString)`.
3744
3745See the POSIX readlink(2) documentation for more details.
3746
3747The optional `options` argument can be a string specifying an encoding, or an
3748object with an `encoding` property specifying the character encoding to use for
3749the link path passed to the callback. If the `encoding` is set to `'buffer'`,
3750the link path returned will be passed as a {Buffer} object.
3751
3752### `fs.readv(fd, buffers[, position], callback)`
3753
3754<!-- YAML
3755added:
3756  - v13.13.0
3757  - v12.17.0
3758changes:
3759  - version: v18.0.0
3760    pr-url: https://github.com/nodejs/node/pull/41678
3761    description: Passing an invalid callback to the `callback` argument
3762                 now throws `ERR_INVALID_ARG_TYPE` instead of
3763                 `ERR_INVALID_CALLBACK`.
3764-->
3765
3766* `fd` {integer}
3767* `buffers` {ArrayBufferView\[]}
3768* `position` {integer|null} **Default:** `null`
3769* `callback` {Function}
3770  * `err` {Error}
3771  * `bytesRead` {integer}
3772  * `buffers` {ArrayBufferView\[]}
3773
3774Read from a file specified by `fd` and write to an array of `ArrayBufferView`s
3775using `readv()`.
3776
3777`position` is the offset from the beginning of the file from where data
3778should be read. If `typeof position !== 'number'`, the data will be read
3779from the current position.
3780
3781The callback will be given three arguments: `err`, `bytesRead`, and
3782`buffers`. `bytesRead` is how many bytes were read from the file.
3783
3784If this method is invoked as its [`util.promisify()`][]ed version, it returns
3785a promise for an `Object` with `bytesRead` and `buffers` properties.
3786
3787### `fs.realpath(path[, options], callback)`
3788
3789<!-- YAML
3790added: v0.1.31
3791changes:
3792  - version: v18.0.0
3793    pr-url: https://github.com/nodejs/node/pull/41678
3794    description: Passing an invalid callback to the `callback` argument
3795                 now throws `ERR_INVALID_ARG_TYPE` instead of
3796                 `ERR_INVALID_CALLBACK`.
3797  - version: v10.0.0
3798    pr-url: https://github.com/nodejs/node/pull/12562
3799    description: The `callback` parameter is no longer optional. Not passing
3800                 it will throw a `TypeError` at runtime.
3801  - version: v8.0.0
3802    pr-url: https://github.com/nodejs/node/pull/13028
3803    description: Pipe/Socket resolve support was added.
3804  - version: v7.6.0
3805    pr-url: https://github.com/nodejs/node/pull/10739
3806    description: The `path` parameter can be a WHATWG `URL` object using
3807                 `file:` protocol.
3808  - version: v7.0.0
3809    pr-url: https://github.com/nodejs/node/pull/7897
3810    description: The `callback` parameter is no longer optional. Not passing
3811                 it will emit a deprecation warning with id DEP0013.
3812  - version: v6.4.0
3813    pr-url: https://github.com/nodejs/node/pull/7899
3814    description: Calling `realpath` now works again for various edge cases
3815                 on Windows.
3816  - version: v6.0.0
3817    pr-url: https://github.com/nodejs/node/pull/3594
3818    description: The `cache` parameter was removed.
3819-->
3820
3821* `path` {string|Buffer|URL}
3822* `options` {string|Object}
3823  * `encoding` {string} **Default:** `'utf8'`
3824* `callback` {Function}
3825  * `err` {Error}
3826  * `resolvedPath` {string|Buffer}
3827
3828Asynchronously computes the canonical pathname by resolving `.`, `..`, and
3829symbolic links.
3830
3831A canonical pathname is not necessarily unique. Hard links and bind mounts can
3832expose a file system entity through many pathnames.
3833
3834This function behaves like realpath(3), with some exceptions:
3835
38361. No case conversion is performed on case-insensitive file systems.
3837
38382. The maximum number of symbolic links is platform-independent and generally
3839   (much) higher than what the native realpath(3) implementation supports.
3840
3841The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`
3842to resolve relative paths.
3843
3844Only paths that can be converted to UTF8 strings are supported.
3845
3846The optional `options` argument can be a string specifying an encoding, or an
3847object with an `encoding` property specifying the character encoding to use for
3848the path passed to the callback. If the `encoding` is set to `'buffer'`,
3849the path returned will be passed as a {Buffer} object.
3850
3851If `path` resolves to a socket or a pipe, the function will return a system
3852dependent name for that object.
3853
3854### `fs.realpath.native(path[, options], callback)`
3855
3856<!-- YAML
3857added: v9.2.0
3858changes:
3859  - version: v18.0.0
3860    pr-url: https://github.com/nodejs/node/pull/41678
3861    description: Passing an invalid callback to the `callback` argument
3862                 now throws `ERR_INVALID_ARG_TYPE` instead of
3863                 `ERR_INVALID_CALLBACK`.
3864-->
3865
3866* `path` {string|Buffer|URL}
3867* `options` {string|Object}
3868  * `encoding` {string} **Default:** `'utf8'`
3869* `callback` {Function}
3870  * `err` {Error}
3871  * `resolvedPath` {string|Buffer}
3872
3873Asynchronous realpath(3).
3874
3875The `callback` gets two arguments `(err, resolvedPath)`.
3876
3877Only paths that can be converted to UTF8 strings are supported.
3878
3879The optional `options` argument can be a string specifying an encoding, or an
3880object with an `encoding` property specifying the character encoding to use for
3881the path passed to the callback. If the `encoding` is set to `'buffer'`,
3882the path returned will be passed as a {Buffer} object.
3883
3884On Linux, when Node.js is linked against musl libc, the procfs file system must
3885be mounted on `/proc` in order for this function to work. Glibc does not have
3886this restriction.
3887
3888### `fs.rename(oldPath, newPath, callback)`
3889
3890<!-- YAML
3891added: v0.0.2
3892changes:
3893  - version: v18.0.0
3894    pr-url: https://github.com/nodejs/node/pull/41678
3895    description: Passing an invalid callback to the `callback` argument
3896                 now throws `ERR_INVALID_ARG_TYPE` instead of
3897                 `ERR_INVALID_CALLBACK`.
3898  - version: v10.0.0
3899    pr-url: https://github.com/nodejs/node/pull/12562
3900    description: The `callback` parameter is no longer optional. Not passing
3901                 it will throw a `TypeError` at runtime.
3902  - version: v7.6.0
3903    pr-url: https://github.com/nodejs/node/pull/10739
3904    description: The `oldPath` and `newPath` parameters can be WHATWG `URL`
3905                 objects using `file:` protocol. Support is currently still
3906                 *experimental*.
3907  - version: v7.0.0
3908    pr-url: https://github.com/nodejs/node/pull/7897
3909    description: The `callback` parameter is no longer optional. Not passing
3910                 it will emit a deprecation warning with id DEP0013.
3911-->
3912
3913* `oldPath` {string|Buffer|URL}
3914* `newPath` {string|Buffer|URL}
3915* `callback` {Function}
3916  * `err` {Error}
3917
3918Asynchronously rename file at `oldPath` to the pathname provided
3919as `newPath`. In the case that `newPath` already exists, it will
3920be overwritten. If there is a directory at `newPath`, an error will
3921be raised instead. No arguments other than a possible exception are
3922given to the completion callback.
3923
3924See also: rename(2).
3925
3926```mjs
3927import { rename } from 'node:fs';
3928
3929rename('oldFile.txt', 'newFile.txt', (err) => {
3930  if (err) throw err;
3931  console.log('Rename complete!');
3932});
3933```
3934
3935### `fs.rmdir(path[, options], callback)`
3936
3937<!-- YAML
3938added: v0.0.2
3939changes:
3940  - version: v18.0.0
3941    pr-url: https://github.com/nodejs/node/pull/41678
3942    description: Passing an invalid callback to the `callback` argument
3943                 now throws `ERR_INVALID_ARG_TYPE` instead of
3944                 `ERR_INVALID_CALLBACK`.
3945  - version: v16.0.0
3946    pr-url: https://github.com/nodejs/node/pull/37216
3947    description: "Using `fs.rmdir(path, { recursive: true })` on a `path` that is
3948                 a file is no longer permitted and results in an `ENOENT` error
3949                 on Windows and an `ENOTDIR` error on POSIX."
3950  - version: v16.0.0
3951    pr-url: https://github.com/nodejs/node/pull/37216
3952    description: "Using `fs.rmdir(path, { recursive: true })` on a `path` that
3953                 does not exist is no longer permitted and results in a `ENOENT`
3954                 error."
3955  - version: v16.0.0
3956    pr-url: https://github.com/nodejs/node/pull/37302
3957    description: The `recursive` option is deprecated, using it triggers a
3958                 deprecation warning.
3959  - version: v14.14.0
3960    pr-url: https://github.com/nodejs/node/pull/35579
3961    description: The `recursive` option is deprecated, use `fs.rm` instead.
3962  - version:
3963     - v13.3.0
3964     - v12.16.0
3965    pr-url: https://github.com/nodejs/node/pull/30644
3966    description: The `maxBusyTries` option is renamed to `maxRetries`, and its
3967                 default is 0. The `emfileWait` option has been removed, and
3968                 `EMFILE` errors use the same retry logic as other errors. The
3969                 `retryDelay` option is now supported. `ENFILE` errors are now
3970                 retried.
3971  - version: v12.10.0
3972    pr-url: https://github.com/nodejs/node/pull/29168
3973    description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
3974                 now supported.
3975  - version: v10.0.0
3976    pr-url: https://github.com/nodejs/node/pull/12562
3977    description: The `callback` parameter is no longer optional. Not passing
3978                 it will throw a `TypeError` at runtime.
3979  - version: v7.6.0
3980    pr-url: https://github.com/nodejs/node/pull/10739
3981    description: The `path` parameters can be a WHATWG `URL` object using
3982                 `file:` protocol.
3983  - version: v7.0.0
3984    pr-url: https://github.com/nodejs/node/pull/7897
3985    description: The `callback` parameter is no longer optional. Not passing
3986                 it will emit a deprecation warning with id DEP0013.
3987-->
3988
3989* `path` {string|Buffer|URL}
3990* `options` {Object}
3991  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
3992    `EPERM` error is encountered, Node.js retries the operation with a linear
3993    backoff wait of `retryDelay` milliseconds longer on each try. This option
3994    represents the number of retries. This option is ignored if the `recursive`
3995    option is not `true`. **Default:** `0`.
3996  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
3997    recursive mode, operations are retried on failure. **Default:** `false`.
3998    **Deprecated.**
3999  * `retryDelay` {integer} The amount of time in milliseconds to wait between
4000    retries. This option is ignored if the `recursive` option is not `true`.
4001    **Default:** `100`.
4002* `callback` {Function}
4003  * `err` {Error}
4004
4005Asynchronous rmdir(2). No arguments other than a possible exception are given
4006to the completion callback.
4007
4008Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on
4009Windows and an `ENOTDIR` error on POSIX.
4010
4011To get a behavior similar to the `rm -rf` Unix command, use [`fs.rm()`][]
4012with options `{ recursive: true, force: true }`.
4013
4014### `fs.rm(path[, options], callback)`
4015
4016<!-- YAML
4017added: v14.14.0
4018changes:
4019  - version:
4020      - v17.3.0
4021      - v16.14.0
4022    pr-url: https://github.com/nodejs/node/pull/41132
4023    description: The `path` parameter can be a WHATWG `URL` object using `file:`
4024                 protocol.
4025-->
4026
4027* `path` {string|Buffer|URL}
4028* `options` {Object}
4029  * `force` {boolean} When `true`, exceptions will be ignored if `path` does
4030    not exist. **Default:** `false`.
4031  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
4032    `EPERM` error is encountered, Node.js will retry the operation with a linear
4033    backoff wait of `retryDelay` milliseconds longer on each try. This option
4034    represents the number of retries. This option is ignored if the `recursive`
4035    option is not `true`. **Default:** `0`.
4036  * `recursive` {boolean} If `true`, perform a recursive removal. In
4037    recursive mode operations are retried on failure. **Default:** `false`.
4038  * `retryDelay` {integer} The amount of time in milliseconds to wait between
4039    retries. This option is ignored if the `recursive` option is not `true`.
4040    **Default:** `100`.
4041* `callback` {Function}
4042  * `err` {Error}
4043
4044Asynchronously removes files and directories (modeled on the standard POSIX `rm`
4045utility). No arguments other than a possible exception are given to the
4046completion callback.
4047
4048### `fs.stat(path[, options], callback)`
4049
4050<!-- YAML
4051added: v0.0.2
4052changes:
4053  - version: v18.0.0
4054    pr-url: https://github.com/nodejs/node/pull/41678
4055    description: Passing an invalid callback to the `callback` argument
4056                 now throws `ERR_INVALID_ARG_TYPE` instead of
4057                 `ERR_INVALID_CALLBACK`.
4058  - version: v10.5.0
4059    pr-url: https://github.com/nodejs/node/pull/20220
4060    description: Accepts an additional `options` object to specify whether
4061                 the numeric values returned should be bigint.
4062  - version: v10.0.0
4063    pr-url: https://github.com/nodejs/node/pull/12562
4064    description: The `callback` parameter is no longer optional. Not passing
4065                 it will throw a `TypeError` at runtime.
4066  - version: v7.6.0
4067    pr-url: https://github.com/nodejs/node/pull/10739
4068    description: The `path` parameter can be a WHATWG `URL` object using `file:`
4069                 protocol.
4070  - version: v7.0.0
4071    pr-url: https://github.com/nodejs/node/pull/7897
4072    description: The `callback` parameter is no longer optional. Not passing
4073                 it will emit a deprecation warning with id DEP0013.
4074-->
4075
4076* `path` {string|Buffer|URL}
4077* `options` {Object}
4078  * `bigint` {boolean} Whether the numeric values in the returned
4079    {fs.Stats} object should be `bigint`. **Default:** `false`.
4080* `callback` {Function}
4081  * `err` {Error}
4082  * `stats` {fs.Stats}
4083
4084Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
4085`stats` is an {fs.Stats} object.
4086
4087In case of an error, the `err.code` will be one of [Common System Errors][].
4088
4089[`fs.stat()`][] follows symbolic links. Use [`fs.lstat()`][] to look at the
4090links themselves.
4091
4092Using `fs.stat()` to check for the existence of a file before calling
4093`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended.
4094Instead, user code should open/read/write the file directly and handle the
4095error raised if the file is not available.
4096
4097To check if a file exists without manipulating it afterwards, [`fs.access()`][]
4098is recommended.
4099
4100For example, given the following directory structure:
4101
4102```text
4103- txtDir
4104-- file.txt
4105- app.js
4106```
4107
4108The next program will check for the stats of the given paths:
4109
4110```mjs
4111import { stat } from 'node:fs';
4112
4113const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
4114
4115for (let i = 0; i < pathsToCheck.length; i++) {
4116  stat(pathsToCheck[i], (err, stats) => {
4117    console.log(stats.isDirectory());
4118    console.log(stats);
4119  });
4120}
4121```
4122
4123The resulting output will resemble:
4124
4125```console
4126true
4127Stats {
4128  dev: 16777220,
4129  mode: 16877,
4130  nlink: 3,
4131  uid: 501,
4132  gid: 20,
4133  rdev: 0,
4134  blksize: 4096,
4135  ino: 14214262,
4136  size: 96,
4137  blocks: 0,
4138  atimeMs: 1561174653071.963,
4139  mtimeMs: 1561174614583.3518,
4140  ctimeMs: 1561174626623.5366,
4141  birthtimeMs: 1561174126937.2893,
4142  atime: 2019-06-22T03:37:33.072Z,
4143  mtime: 2019-06-22T03:36:54.583Z,
4144  ctime: 2019-06-22T03:37:06.624Z,
4145  birthtime: 2019-06-22T03:28:46.937Z
4146}
4147false
4148Stats {
4149  dev: 16777220,
4150  mode: 33188,
4151  nlink: 1,
4152  uid: 501,
4153  gid: 20,
4154  rdev: 0,
4155  blksize: 4096,
4156  ino: 14214074,
4157  size: 8,
4158  blocks: 8,
4159  atimeMs: 1561174616618.8555,
4160  mtimeMs: 1561174614584,
4161  ctimeMs: 1561174614583.8145,
4162  birthtimeMs: 1561174007710.7478,
4163  atime: 2019-06-22T03:36:56.619Z,
4164  mtime: 2019-06-22T03:36:54.584Z,
4165  ctime: 2019-06-22T03:36:54.584Z,
4166  birthtime: 2019-06-22T03:26:47.711Z
4167}
4168```
4169
4170### `fs.statfs(path[, options], callback)`
4171
4172<!-- YAML
4173added: v18.15.0
4174-->
4175
4176* `path` {string|Buffer|URL}
4177* `options` {Object}
4178  * `bigint` {boolean} Whether the numeric values in the returned
4179    {fs.StatFs} object should be `bigint`. **Default:** `false`.
4180* `callback` {Function}
4181  * `err` {Error}
4182  * `stats` {fs.StatFs}
4183
4184Asynchronous statfs(2). Returns information about the mounted file system which
4185contains `path`. The callback gets two arguments `(err, stats)` where `stats`
4186is an {fs.StatFs} object.
4187
4188In case of an error, the `err.code` will be one of [Common System Errors][].
4189
4190### `fs.symlink(target, path[, type], callback)`
4191
4192<!-- YAML
4193added: v0.1.31
4194changes:
4195  - version: v18.0.0
4196    pr-url: https://github.com/nodejs/node/pull/41678
4197    description: Passing an invalid callback to the `callback` argument
4198                 now throws `ERR_INVALID_ARG_TYPE` instead of
4199                 `ERR_INVALID_CALLBACK`.
4200  - version: v12.0.0
4201    pr-url: https://github.com/nodejs/node/pull/23724
4202    description: If the `type` argument is left undefined, Node will autodetect
4203                 `target` type and automatically select `dir` or `file`.
4204  - version: v7.6.0
4205    pr-url: https://github.com/nodejs/node/pull/10739
4206    description: The `target` and `path` parameters can be WHATWG `URL` objects
4207                 using `file:` protocol. Support is currently still
4208                 *experimental*.
4209-->
4210
4211* `target` {string|Buffer|URL}
4212* `path` {string|Buffer|URL}
4213* `type` {string|null} **Default:** `null`
4214* `callback` {Function}
4215  * `err` {Error}
4216
4217Creates the link called `path` pointing to `target`. No arguments other than a
4218possible exception are given to the completion callback.
4219
4220See the POSIX symlink(2) documentation for more details.
4221
4222The `type` argument is only available on Windows and ignored on other platforms.
4223It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is
4224not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`.
4225If the `target` does not exist, `'file'` will be used. Windows junction points
4226require the destination path to be absolute. When using `'junction'`, the
4227`target` argument will automatically be normalized to absolute path. Junction
4228points on NTFS volumes can only point to directories.
4229
4230Relative targets are relative to the link's parent directory.
4231
4232```mjs
4233import { symlink } from 'node:fs';
4234
4235symlink('./mew', './mewtwo', callback);
4236```
4237
4238The above example creates a symbolic link `mewtwo` which points to `mew` in the
4239same directory:
4240
4241```bash
4242$ tree .
4243.
4244├── mew
4245└── mewtwo -> ./mew
4246```
4247
4248### `fs.truncate(path[, len], callback)`
4249
4250<!-- YAML
4251added: v0.8.6
4252changes:
4253  - version: v18.0.0
4254    pr-url: https://github.com/nodejs/node/pull/41678
4255    description: Passing an invalid callback to the `callback` argument
4256                 now throws `ERR_INVALID_ARG_TYPE` instead of
4257                 `ERR_INVALID_CALLBACK`.
4258  - version: v16.0.0
4259    pr-url: https://github.com/nodejs/node/pull/37460
4260    description: The error returned may be an `AggregateError` if more than one
4261                 error is returned.
4262  - version: v10.0.0
4263    pr-url: https://github.com/nodejs/node/pull/12562
4264    description: The `callback` parameter is no longer optional. Not passing
4265                 it will throw a `TypeError` at runtime.
4266  - version: v7.0.0
4267    pr-url: https://github.com/nodejs/node/pull/7897
4268    description: The `callback` parameter is no longer optional. Not passing
4269                 it will emit a deprecation warning with id DEP0013.
4270-->
4271
4272* `path` {string|Buffer|URL}
4273* `len` {integer} **Default:** `0`
4274* `callback` {Function}
4275  * `err` {Error|AggregateError}
4276
4277Truncates the file. No arguments other than a possible exception are
4278given to the completion callback. A file descriptor can also be passed as the
4279first argument. In this case, `fs.ftruncate()` is called.
4280
4281```mjs
4282import { truncate } from 'node:fs';
4283// Assuming that 'path/file.txt' is a regular file.
4284truncate('path/file.txt', (err) => {
4285  if (err) throw err;
4286  console.log('path/file.txt was truncated');
4287});
4288```
4289
4290```cjs
4291const { truncate } = require('node:fs');
4292// Assuming that 'path/file.txt' is a regular file.
4293truncate('path/file.txt', (err) => {
4294  if (err) throw err;
4295  console.log('path/file.txt was truncated');
4296});
4297```
4298
4299Passing a file descriptor is deprecated and may result in an error being thrown
4300in the future.
4301
4302See the POSIX truncate(2) documentation for more details.
4303
4304### `fs.unlink(path, callback)`
4305
4306<!-- YAML
4307added: v0.0.2
4308changes:
4309  - version: v18.0.0
4310    pr-url: https://github.com/nodejs/node/pull/41678
4311    description: Passing an invalid callback to the `callback` argument
4312                 now throws `ERR_INVALID_ARG_TYPE` instead of
4313                 `ERR_INVALID_CALLBACK`.
4314  - version: v10.0.0
4315    pr-url: https://github.com/nodejs/node/pull/12562
4316    description: The `callback` parameter is no longer optional. Not passing
4317                 it will throw a `TypeError` at runtime.
4318  - version: v7.6.0
4319    pr-url: https://github.com/nodejs/node/pull/10739
4320    description: The `path` parameter can be a WHATWG `URL` object using `file:`
4321                 protocol.
4322  - version: v7.0.0
4323    pr-url: https://github.com/nodejs/node/pull/7897
4324    description: The `callback` parameter is no longer optional. Not passing
4325                 it will emit a deprecation warning with id DEP0013.
4326-->
4327
4328* `path` {string|Buffer|URL}
4329* `callback` {Function}
4330  * `err` {Error}
4331
4332Asynchronously removes a file or symbolic link. No arguments other than a
4333possible exception are given to the completion callback.
4334
4335```mjs
4336import { unlink } from 'node:fs';
4337// Assuming that 'path/file.txt' is a regular file.
4338unlink('path/file.txt', (err) => {
4339  if (err) throw err;
4340  console.log('path/file.txt was deleted');
4341});
4342```
4343
4344`fs.unlink()` will not work on a directory, empty or otherwise. To remove a
4345directory, use [`fs.rmdir()`][].
4346
4347See the POSIX unlink(2) documentation for more details.
4348
4349### `fs.unwatchFile(filename[, listener])`
4350
4351<!-- YAML
4352added: v0.1.31
4353-->
4354
4355* `filename` {string|Buffer|URL}
4356* `listener` {Function} Optional, a listener previously attached using
4357  `fs.watchFile()`
4358
4359Stop watching for changes on `filename`. If `listener` is specified, only that
4360particular listener is removed. Otherwise, _all_ listeners are removed,
4361effectively stopping watching of `filename`.
4362
4363Calling `fs.unwatchFile()` with a filename that is not being watched is a
4364no-op, not an error.
4365
4366Using [`fs.watch()`][] is more efficient than `fs.watchFile()` and
4367`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`
4368and `fs.unwatchFile()` when possible.
4369
4370### `fs.utimes(path, atime, mtime, callback)`
4371
4372<!-- YAML
4373added: v0.4.2
4374changes:
4375  - version: v18.0.0
4376    pr-url: https://github.com/nodejs/node/pull/41678
4377    description: Passing an invalid callback to the `callback` argument
4378                 now throws `ERR_INVALID_ARG_TYPE` instead of
4379                 `ERR_INVALID_CALLBACK`.
4380  - version: v10.0.0
4381    pr-url: https://github.com/nodejs/node/pull/12562
4382    description: The `callback` parameter is no longer optional. Not passing
4383                 it will throw a `TypeError` at runtime.
4384  - version: v8.0.0
4385    pr-url: https://github.com/nodejs/node/pull/11919
4386    description: "`NaN`, `Infinity`, and `-Infinity` are no longer valid time
4387                 specifiers."
4388  - version: v7.6.0
4389    pr-url: https://github.com/nodejs/node/pull/10739
4390    description: The `path` parameter can be a WHATWG `URL` object using `file:`
4391                 protocol.
4392  - version: v7.0.0
4393    pr-url: https://github.com/nodejs/node/pull/7897
4394    description: The `callback` parameter is no longer optional. Not passing
4395                 it will emit a deprecation warning with id DEP0013.
4396  - version: v4.1.0
4397    pr-url: https://github.com/nodejs/node/pull/2387
4398    description: Numeric strings, `NaN`, and `Infinity` are now allowed
4399                 time specifiers.
4400-->
4401
4402* `path` {string|Buffer|URL}
4403* `atime` {number|string|Date}
4404* `mtime` {number|string|Date}
4405* `callback` {Function}
4406  * `err` {Error}
4407
4408Change the file system timestamps of the object referenced by `path`.
4409
4410The `atime` and `mtime` arguments follow these rules:
4411
4412* Values can be either numbers representing Unix epoch time in seconds,
4413  `Date`s, or a numeric string like `'123456789.0'`.
4414* If the value can not be converted to a number, or is `NaN`, `Infinity`, or
4415  `-Infinity`, an `Error` will be thrown.
4416
4417### `fs.watch(filename[, options][, listener])`
4418
4419<!-- YAML
4420added: v0.5.10
4421changes:
4422  - version:
4423      - v15.9.0
4424      - v14.17.0
4425    pr-url: https://github.com/nodejs/node/pull/37190
4426    description: Added support for closing the watcher with an AbortSignal.
4427  - version: v7.6.0
4428    pr-url: https://github.com/nodejs/node/pull/10739
4429    description: The `filename` parameter can be a WHATWG `URL` object using
4430                 `file:` protocol.
4431  - version: v7.0.0
4432    pr-url: https://github.com/nodejs/node/pull/7831
4433    description: The passed `options` object will never be modified.
4434-->
4435
4436* `filename` {string|Buffer|URL}
4437* `options` {string|Object}
4438  * `persistent` {boolean} Indicates whether the process should continue to run
4439    as long as files are being watched. **Default:** `true`.
4440  * `recursive` {boolean} Indicates whether all subdirectories should be
4441    watched, or only the current directory. This applies when a directory is
4442    specified, and only on supported platforms (See [caveats][]). **Default:**
4443    `false`.
4444  * `encoding` {string} Specifies the character encoding to be used for the
4445    filename passed to the listener. **Default:** `'utf8'`.
4446  * `signal` {AbortSignal} allows closing the watcher with an AbortSignal.
4447* `listener` {Function|undefined} **Default:** `undefined`
4448  * `eventType` {string}
4449  * `filename` {string|Buffer|null}
4450* Returns: {fs.FSWatcher}
4451
4452Watch for changes on `filename`, where `filename` is either a file or a
4453directory.
4454
4455The second argument is optional. If `options` is provided as a string, it
4456specifies the `encoding`. Otherwise `options` should be passed as an object.
4457
4458The listener callback gets two arguments `(eventType, filename)`. `eventType`
4459is either `'rename'` or `'change'`, and `filename` is the name of the file
4460which triggered the event.
4461
4462On most platforms, `'rename'` is emitted whenever a filename appears or
4463disappears in the directory.
4464
4465The listener callback is attached to the `'change'` event fired by
4466{fs.FSWatcher}, but it is not the same thing as the `'change'` value of
4467`eventType`.
4468
4469If a `signal` is passed, aborting the corresponding AbortController will close
4470the returned {fs.FSWatcher}.
4471
4472#### Caveats
4473
4474<!--type=misc-->
4475
4476The `fs.watch` API is not 100% consistent across platforms, and is
4477unavailable in some situations.
4478
4479The recursive option is only supported on macOS and Windows.
4480An `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` exception will be thrown
4481when the option is used on a platform that does not support it.
4482
4483On Windows, no events will be emitted if the watched directory is moved or
4484renamed. An `EPERM` error is reported when the watched directory is deleted.
4485
4486##### Availability
4487
4488<!--type=misc-->
4489
4490This feature depends on the underlying operating system providing a way
4491to be notified of file system changes.
4492
4493* On Linux systems, this uses [`inotify(7)`][].
4494* On BSD systems, this uses [`kqueue(2)`][].
4495* On macOS, this uses [`kqueue(2)`][] for files and [`FSEvents`][] for
4496  directories.
4497* On SunOS systems (including Solaris and SmartOS), this uses [`event ports`][].
4498* On Windows systems, this feature depends on [`ReadDirectoryChangesW`][].
4499* On AIX systems, this feature depends on [`AHAFS`][], which must be enabled.
4500* On IBM i systems, this feature is not supported.
4501
4502If the underlying functionality is not available for some reason, then
4503`fs.watch()` will not be able to function and may throw an exception.
4504For example, watching files or directories can be unreliable, and in some
4505cases impossible, on network file systems (NFS, SMB, etc) or host file systems
4506when using virtualization software such as Vagrant or Docker.
4507
4508It is still possible to use `fs.watchFile()`, which uses stat polling, but
4509this method is slower and less reliable.
4510
4511##### Inodes
4512
4513<!--type=misc-->
4514
4515On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and
4516watches the inode. If the watched path is deleted and recreated, it is assigned
4517a new inode. The watch will emit an event for the delete but will continue
4518watching the _original_ inode. Events for the new inode will not be emitted.
4519This is expected behavior.
4520
4521AIX files retain the same inode for the lifetime of a file. Saving and closing a
4522watched file on AIX will result in two notifications (one for adding new
4523content, and one for truncation).
4524
4525##### Filename argument
4526
4527<!--type=misc-->
4528
4529Providing `filename` argument in the callback is only supported on Linux,
4530macOS, Windows, and AIX. Even on supported platforms, `filename` is not always
4531guaranteed to be provided. Therefore, don't assume that `filename` argument is
4532always provided in the callback, and have some fallback logic if it is `null`.
4533
4534```mjs
4535import { watch } from 'node:fs';
4536watch('somedir', (eventType, filename) => {
4537  console.log(`event type is: ${eventType}`);
4538  if (filename) {
4539    console.log(`filename provided: ${filename}`);
4540  } else {
4541    console.log('filename not provided');
4542  }
4543});
4544```
4545
4546### `fs.watchFile(filename[, options], listener)`
4547
4548<!-- YAML
4549added: v0.1.31
4550changes:
4551  - version: v10.5.0
4552    pr-url: https://github.com/nodejs/node/pull/20220
4553    description: The `bigint` option is now supported.
4554  - version: v7.6.0
4555    pr-url: https://github.com/nodejs/node/pull/10739
4556    description: The `filename` parameter can be a WHATWG `URL` object using
4557                 `file:` protocol.
4558-->
4559
4560* `filename` {string|Buffer|URL}
4561* `options` {Object}
4562  * `bigint` {boolean} **Default:** `false`
4563  * `persistent` {boolean} **Default:** `true`
4564  * `interval` {integer} **Default:** `5007`
4565* `listener` {Function}
4566  * `current` {fs.Stats}
4567  * `previous` {fs.Stats}
4568* Returns: {fs.StatWatcher}
4569
4570Watch for changes on `filename`. The callback `listener` will be called each
4571time the file is accessed.
4572
4573The `options` argument may be omitted. If provided, it should be an object. The
4574`options` object may contain a boolean named `persistent` that indicates
4575whether the process should continue to run as long as files are being watched.
4576The `options` object may specify an `interval` property indicating how often the
4577target should be polled in milliseconds.
4578
4579The `listener` gets two arguments the current stat object and the previous
4580stat object:
4581
4582```mjs
4583import { watchFile } from 'node:fs';
4584
4585watchFile('message.text', (curr, prev) => {
4586  console.log(`the current mtime is: ${curr.mtime}`);
4587  console.log(`the previous mtime was: ${prev.mtime}`);
4588});
4589```
4590
4591These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
4592the numeric values in these objects are specified as `BigInt`s.
4593
4594To be notified when the file was modified, not just accessed, it is necessary
4595to compare `curr.mtimeMs` and `prev.mtimeMs`.
4596
4597When an `fs.watchFile` operation results in an `ENOENT` error, it
4598will invoke the listener once, with all the fields zeroed (or, for dates, the
4599Unix Epoch). If the file is created later on, the listener will be called
4600again, with the latest stat objects. This is a change in functionality since
4601v0.10.
4602
4603Using [`fs.watch()`][] is more efficient than `fs.watchFile` and
4604`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and
4605`fs.unwatchFile` when possible.
4606
4607When a file being watched by `fs.watchFile()` disappears and reappears,
4608then the contents of `previous` in the second callback event (the file's
4609reappearance) will be the same as the contents of `previous` in the first
4610callback event (its disappearance).
4611
4612This happens when:
4613
4614* the file is deleted, followed by a restore
4615* the file is renamed and then renamed a second time back to its original name
4616
4617### `fs.write(fd, buffer, offset[, length[, position]], callback)`
4618
4619<!-- YAML
4620added: v0.0.2
4621changes:
4622  - version: v18.0.0
4623    pr-url: https://github.com/nodejs/node/pull/41678
4624    description: Passing an invalid callback to the `callback` argument
4625                 now throws `ERR_INVALID_ARG_TYPE` instead of
4626                 `ERR_INVALID_CALLBACK`.
4627  - version: v14.0.0
4628    pr-url: https://github.com/nodejs/node/pull/31030
4629    description: The `buffer` parameter won't coerce unsupported input to
4630                 strings anymore.
4631  - version: v10.10.0
4632    pr-url: https://github.com/nodejs/node/pull/22150
4633    description: The `buffer` parameter can now be any `TypedArray` or a
4634                 `DataView`.
4635  - version: v10.0.0
4636    pr-url: https://github.com/nodejs/node/pull/12562
4637    description: The `callback` parameter is no longer optional. Not passing
4638                 it will throw a `TypeError` at runtime.
4639  - version: v7.4.0
4640    pr-url: https://github.com/nodejs/node/pull/10382
4641    description: The `buffer` parameter can now be a `Uint8Array`.
4642  - version: v7.2.0
4643    pr-url: https://github.com/nodejs/node/pull/7856
4644    description: The `offset` and `length` parameters are optional now.
4645  - version: v7.0.0
4646    pr-url: https://github.com/nodejs/node/pull/7897
4647    description: The `callback` parameter is no longer optional. Not passing
4648                 it will emit a deprecation warning with id DEP0013.
4649-->
4650
4651* `fd` {integer}
4652* `buffer` {Buffer|TypedArray|DataView}
4653* `offset` {integer} **Default:** `0`
4654* `length` {integer} **Default:** `buffer.byteLength - offset`
4655* `position` {integer|null} **Default:** `null`
4656* `callback` {Function}
4657  * `err` {Error}
4658  * `bytesWritten` {integer}
4659  * `buffer` {Buffer|TypedArray|DataView}
4660
4661Write `buffer` to the file specified by `fd`.
4662
4663`offset` determines the part of the buffer to be written, and `length` is
4664an integer specifying the number of bytes to write.
4665
4666`position` refers to the offset from the beginning of the file where this data
4667should be written. If `typeof position !== 'number'`, the data will be written
4668at the current position. See pwrite(2).
4669
4670The callback will be given three arguments `(err, bytesWritten, buffer)` where
4671`bytesWritten` specifies how many _bytes_ were written from `buffer`.
4672
4673If this method is invoked as its [`util.promisify()`][]ed version, it returns
4674a promise for an `Object` with `bytesWritten` and `buffer` properties.
4675
4676It is unsafe to use `fs.write()` multiple times on the same file without waiting
4677for the callback. For this scenario, [`fs.createWriteStream()`][] is
4678recommended.
4679
4680On Linux, positional writes don't work when the file is opened in append mode.
4681The kernel ignores the position argument and always appends the data to
4682the end of the file.
4683
4684### `fs.write(fd, buffer[, options], callback)`
4685
4686<!-- YAML
4687added: v18.3.0
4688-->
4689
4690* `fd` {integer}
4691* `buffer` {Buffer|TypedArray|DataView}
4692* `options` {Object}
4693  * `offset` {integer} **Default:** `0`
4694  * `length` {integer} **Default:** `buffer.byteLength - offset`
4695  * `position` {integer} **Default:** `null`
4696* `callback` {Function}
4697  * `err` {Error}
4698  * `bytesWritten` {integer}
4699  * `buffer` {Buffer|TypedArray|DataView}
4700
4701Write `buffer` to the file specified by `fd`.
4702
4703Similar to the above `fs.write` function, this version takes an
4704optional `options` object. If no `options` object is specified, it will
4705default with the above values.
4706
4707### `fs.write(fd, string[, position[, encoding]], callback)`
4708
4709<!-- YAML
4710added: v0.11.5
4711changes:
4712  - version: v17.8.0
4713    pr-url: https://github.com/nodejs/node/pull/42149
4714    description: Passing to the `string` parameter an object with an own
4715                 `toString` function is deprecated.
4716  - version: v14.12.0
4717    pr-url: https://github.com/nodejs/node/pull/34993
4718    description: The `string` parameter will stringify an object with an
4719                 explicit `toString` function.
4720  - version: v14.0.0
4721    pr-url: https://github.com/nodejs/node/pull/31030
4722    description: The `string` parameter won't coerce unsupported input to
4723                 strings anymore.
4724  - version: v10.0.0
4725    pr-url: https://github.com/nodejs/node/pull/12562
4726    description: The `callback` parameter is no longer optional. Not passing
4727                 it will throw a `TypeError` at runtime.
4728  - version: v7.2.0
4729    pr-url: https://github.com/nodejs/node/pull/7856
4730    description: The `position` parameter is optional now.
4731  - version: v7.0.0
4732    pr-url: https://github.com/nodejs/node/pull/7897
4733    description: The `callback` parameter is no longer optional. Not passing
4734                 it will emit a deprecation warning with id DEP0013.
4735-->
4736
4737* `fd` {integer}
4738* `string` {string|Object}
4739* `position` {integer|null} **Default:** `null`
4740* `encoding` {string} **Default:** `'utf8'`
4741* `callback` {Function}
4742  * `err` {Error}
4743  * `written` {integer}
4744  * `string` {string}
4745
4746Write `string` to the file specified by `fd`. If `string` is not a string, or an
4747object with an own `toString` function property, then an exception is thrown.
4748
4749`position` refers to the offset from the beginning of the file where this data
4750should be written. If `typeof position !== 'number'` the data will be written at
4751the current position. See pwrite(2).
4752
4753`encoding` is the expected string encoding.
4754
4755The callback will receive the arguments `(err, written, string)` where `written`
4756specifies how many _bytes_ the passed string required to be written. Bytes
4757written is not necessarily the same as string characters written. See
4758[`Buffer.byteLength`][].
4759
4760It is unsafe to use `fs.write()` multiple times on the same file without waiting
4761for the callback. For this scenario, [`fs.createWriteStream()`][] is
4762recommended.
4763
4764On Linux, positional writes don't work when the file is opened in append mode.
4765The kernel ignores the position argument and always appends the data to
4766the end of the file.
4767
4768On Windows, if the file descriptor is connected to the console (e.g. `fd == 1`
4769or `stdout`) a string containing non-ASCII characters will not be rendered
4770properly by default, regardless of the encoding used.
4771It is possible to configure the console to render UTF-8 properly by changing the
4772active codepage with the `chcp 65001` command. See the [chcp][] docs for more
4773details.
4774
4775### `fs.writeFile(file, data[, options], callback)`
4776
4777<!-- YAML
4778added: v0.1.29
4779changes:
4780  - version: v18.0.0
4781    pr-url: https://github.com/nodejs/node/pull/41678
4782    description: Passing an invalid callback to the `callback` argument
4783                 now throws `ERR_INVALID_ARG_TYPE` instead of
4784                 `ERR_INVALID_CALLBACK`.
4785  - version: v17.8.0
4786    pr-url: https://github.com/nodejs/node/pull/42149
4787    description: Passing to the `string` parameter an object with an own
4788                 `toString` function is deprecated.
4789  - version: v16.0.0
4790    pr-url: https://github.com/nodejs/node/pull/37460
4791    description: The error returned may be an `AggregateError` if more than one
4792                 error is returned.
4793  - version:
4794      - v15.2.0
4795      - v14.17.0
4796    pr-url: https://github.com/nodejs/node/pull/35993
4797    description: The options argument may include an AbortSignal to abort an
4798                 ongoing writeFile request.
4799  - version: v14.12.0
4800    pr-url: https://github.com/nodejs/node/pull/34993
4801    description: The `data` parameter will stringify an object with an
4802                 explicit `toString` function.
4803  - version: v14.0.0
4804    pr-url: https://github.com/nodejs/node/pull/31030
4805    description: The `data` parameter won't coerce unsupported input to
4806                 strings anymore.
4807  - version: v10.10.0
4808    pr-url: https://github.com/nodejs/node/pull/22150
4809    description: The `data` parameter can now be any `TypedArray` or a
4810                 `DataView`.
4811  - version: v10.0.0
4812    pr-url: https://github.com/nodejs/node/pull/12562
4813    description: The `callback` parameter is no longer optional. Not passing
4814                 it will throw a `TypeError` at runtime.
4815  - version: v7.4.0
4816    pr-url: https://github.com/nodejs/node/pull/10382
4817    description: The `data` parameter can now be a `Uint8Array`.
4818  - version: v7.0.0
4819    pr-url: https://github.com/nodejs/node/pull/7897
4820    description: The `callback` parameter is no longer optional. Not passing
4821                 it will emit a deprecation warning with id DEP0013.
4822  - version: v5.0.0
4823    pr-url: https://github.com/nodejs/node/pull/3163
4824    description: The `file` parameter can be a file descriptor now.
4825-->
4826
4827* `file` {string|Buffer|URL|integer} filename or file descriptor
4828* `data` {string|Buffer|TypedArray|DataView|Object}
4829* `options` {Object|string}
4830  * `encoding` {string|null} **Default:** `'utf8'`
4831  * `mode` {integer} **Default:** `0o666`
4832  * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.
4833  * `signal` {AbortSignal} allows aborting an in-progress writeFile
4834* `callback` {Function}
4835  * `err` {Error|AggregateError}
4836
4837When `file` is a filename, asynchronously writes data to the file, replacing the
4838file if it already exists. `data` can be a string or a buffer.
4839
4840When `file` is a file descriptor, the behavior is similar to calling
4841`fs.write()` directly (which is recommended). See the notes below on using
4842a file descriptor.
4843
4844The `encoding` option is ignored if `data` is a buffer.
4845
4846The `mode` option only affects the newly created file. See [`fs.open()`][]
4847for more details.
4848
4849```mjs
4850import { writeFile } from 'node:fs';
4851import { Buffer } from 'node:buffer';
4852
4853const data = new Uint8Array(Buffer.from('Hello Node.js'));
4854writeFile('message.txt', data, (err) => {
4855  if (err) throw err;
4856  console.log('The file has been saved!');
4857});
4858```
4859
4860If `options` is a string, then it specifies the encoding:
4861
4862```mjs
4863import { writeFile } from 'node:fs';
4864
4865writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
4866```
4867
4868It is unsafe to use `fs.writeFile()` multiple times on the same file without
4869waiting for the callback. For this scenario, [`fs.createWriteStream()`][] is
4870recommended.
4871
4872Similarly to `fs.readFile` - `fs.writeFile` is a convenience method that
4873performs multiple `write` calls internally to write the buffer passed to it.
4874For performance sensitive code consider using [`fs.createWriteStream()`][].
4875
4876It is possible to use an {AbortSignal} to cancel an `fs.writeFile()`.
4877Cancelation is "best effort", and some amount of data is likely still
4878to be written.
4879
4880```mjs
4881import { writeFile } from 'node:fs';
4882import { Buffer } from 'node:buffer';
4883
4884const controller = new AbortController();
4885const { signal } = controller;
4886const data = new Uint8Array(Buffer.from('Hello Node.js'));
4887writeFile('message.txt', data, { signal }, (err) => {
4888  // When a request is aborted - the callback is called with an AbortError
4889});
4890// When the request should be aborted
4891controller.abort();
4892```
4893
4894Aborting an ongoing request does not abort individual operating
4895system requests but rather the internal buffering `fs.writeFile` performs.
4896
4897#### Using `fs.writeFile()` with file descriptors
4898
4899When `file` is a file descriptor, the behavior is almost identical to directly
4900calling `fs.write()` like:
4901
4902```mjs
4903import { write } from 'node:fs';
4904import { Buffer } from 'node:buffer';
4905
4906write(fd, Buffer.from(data, options.encoding), callback);
4907```
4908
4909The difference from directly calling `fs.write()` is that under some unusual
4910conditions, `fs.write()` might write only part of the buffer and need to be
4911retried to write the remaining data, whereas `fs.writeFile()` retries until
4912the data is entirely written (or an error occurs).
4913
4914The implications of this are a common source of confusion. In
4915the file descriptor case, the file is not replaced! The data is not necessarily
4916written to the beginning of the file, and the file's original data may remain
4917before and/or after the newly written data.
4918
4919For example, if `fs.writeFile()` is called twice in a row, first to write the
4920string `'Hello'`, then to write the string `', World'`, the file would contain
4921`'Hello, World'`, and might contain some of the file's original data (depending
4922on the size of the original file, and the position of the file descriptor). If
4923a file name had been used instead of a descriptor, the file would be guaranteed
4924to contain only `', World'`.
4925
4926### `fs.writev(fd, buffers[, position], callback)`
4927
4928<!-- YAML
4929added: v12.9.0
4930changes:
4931  - version: v18.0.0
4932    pr-url: https://github.com/nodejs/node/pull/41678
4933    description: Passing an invalid callback to the `callback` argument
4934                 now throws `ERR_INVALID_ARG_TYPE` instead of
4935                 `ERR_INVALID_CALLBACK`.
4936-->
4937
4938* `fd` {integer}
4939* `buffers` {ArrayBufferView\[]}
4940* `position` {integer|null} **Default:** `null`
4941* `callback` {Function}
4942  * `err` {Error}
4943  * `bytesWritten` {integer}
4944  * `buffers` {ArrayBufferView\[]}
4945
4946Write an array of `ArrayBufferView`s to the file specified by `fd` using
4947`writev()`.
4948
4949`position` is the offset from the beginning of the file where this data
4950should be written. If `typeof position !== 'number'`, the data will be written
4951at the current position.
4952
4953The callback will be given three arguments: `err`, `bytesWritten`, and
4954`buffers`. `bytesWritten` is how many bytes were written from `buffers`.
4955
4956If this method is [`util.promisify()`][]ed, it returns a promise for an
4957`Object` with `bytesWritten` and `buffers` properties.
4958
4959It is unsafe to use `fs.writev()` multiple times on the same file without
4960waiting for the callback. For this scenario, use [`fs.createWriteStream()`][].
4961
4962On Linux, positional writes don't work when the file is opened in append mode.
4963The kernel ignores the position argument and always appends the data to
4964the end of the file.
4965
4966## Synchronous API
4967
4968The synchronous APIs perform all operations synchronously, blocking the
4969event loop until the operation completes or fails.
4970
4971### `fs.accessSync(path[, mode])`
4972
4973<!-- YAML
4974added: v0.11.15
4975changes:
4976  - version: v7.6.0
4977    pr-url: https://github.com/nodejs/node/pull/10739
4978    description: The `path` parameter can be a WHATWG `URL` object using `file:`
4979                 protocol.
4980-->
4981
4982* `path` {string|Buffer|URL}
4983* `mode` {integer} **Default:** `fs.constants.F_OK`
4984
4985Synchronously tests a user's permissions for the file or directory specified
4986by `path`. The `mode` argument is an optional integer that specifies the
4987accessibility checks to be performed. `mode` should be either the value
4988`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of
4989`fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.
4990`fs.constants.W_OK | fs.constants.R_OK`). Check [File access constants][] for
4991possible values of `mode`.
4992
4993If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
4994the method will return `undefined`.
4995
4996```mjs
4997import { accessSync, constants } from 'node:fs';
4998
4999try {
5000  accessSync('etc/passwd', constants.R_OK | constants.W_OK);
5001  console.log('can read/write');
5002} catch (err) {
5003  console.error('no access!');
5004}
5005```
5006
5007### `fs.appendFileSync(path, data[, options])`
5008
5009<!-- YAML
5010added: v0.6.7
5011changes:
5012  - version: v7.0.0
5013    pr-url: https://github.com/nodejs/node/pull/7831
5014    description: The passed `options` object will never be modified.
5015  - version: v5.0.0
5016    pr-url: https://github.com/nodejs/node/pull/3163
5017    description: The `file` parameter can be a file descriptor now.
5018-->
5019
5020* `path` {string|Buffer|URL|number} filename or file descriptor
5021* `data` {string|Buffer}
5022* `options` {Object|string}
5023  * `encoding` {string|null} **Default:** `'utf8'`
5024  * `mode` {integer} **Default:** `0o666`
5025  * `flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.
5026
5027Synchronously append data to a file, creating the file if it does not yet
5028exist. `data` can be a string or a {Buffer}.
5029
5030The `mode` option only affects the newly created file. See [`fs.open()`][]
5031for more details.
5032
5033```mjs
5034import { appendFileSync } from 'node:fs';
5035
5036try {
5037  appendFileSync('message.txt', 'data to append');
5038  console.log('The "data to append" was appended to file!');
5039} catch (err) {
5040  /* Handle the error */
5041}
5042```
5043
5044If `options` is a string, then it specifies the encoding:
5045
5046```mjs
5047import { appendFileSync } from 'node:fs';
5048
5049appendFileSync('message.txt', 'data to append', 'utf8');
5050```
5051
5052The `path` may be specified as a numeric file descriptor that has been opened
5053for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
5054not be closed automatically.
5055
5056```mjs
5057import { openSync, closeSync, appendFileSync } from 'node:fs';
5058
5059let fd;
5060
5061try {
5062  fd = openSync('message.txt', 'a');
5063  appendFileSync(fd, 'data to append', 'utf8');
5064} catch (err) {
5065  /* Handle the error */
5066} finally {
5067  if (fd !== undefined)
5068    closeSync(fd);
5069}
5070```
5071
5072### `fs.chmodSync(path, mode)`
5073
5074<!-- YAML
5075added: v0.6.7
5076changes:
5077  - version: v7.6.0
5078    pr-url: https://github.com/nodejs/node/pull/10739
5079    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5080                 protocol.
5081-->
5082
5083* `path` {string|Buffer|URL}
5084* `mode` {string|integer}
5085
5086For detailed information, see the documentation of the asynchronous version of
5087this API: [`fs.chmod()`][].
5088
5089See the POSIX chmod(2) documentation for more detail.
5090
5091### `fs.chownSync(path, uid, gid)`
5092
5093<!-- YAML
5094added: v0.1.97
5095changes:
5096  - version: v7.6.0
5097    pr-url: https://github.com/nodejs/node/pull/10739
5098    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5099                 protocol.
5100-->
5101
5102* `path` {string|Buffer|URL}
5103* `uid` {integer}
5104* `gid` {integer}
5105
5106Synchronously changes owner and group of a file. Returns `undefined`.
5107This is the synchronous version of [`fs.chown()`][].
5108
5109See the POSIX chown(2) documentation for more detail.
5110
5111### `fs.closeSync(fd)`
5112
5113<!-- YAML
5114added: v0.1.21
5115-->
5116
5117* `fd` {integer}
5118
5119Closes the file descriptor. Returns `undefined`.
5120
5121Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use
5122through any other `fs` operation may lead to undefined behavior.
5123
5124See the POSIX close(2) documentation for more detail.
5125
5126### `fs.copyFileSync(src, dest[, mode])`
5127
5128<!-- YAML
5129added: v8.5.0
5130changes:
5131  - version: v14.0.0
5132    pr-url: https://github.com/nodejs/node/pull/27044
5133    description: Changed `flags` argument to `mode` and imposed
5134                 stricter type validation.
5135-->
5136
5137* `src` {string|Buffer|URL} source filename to copy
5138* `dest` {string|Buffer|URL} destination filename of the copy operation
5139* `mode` {integer} modifiers for copy operation. **Default:** `0`.
5140
5141Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
5142already exists. Returns `undefined`. Node.js makes no guarantees about the
5143atomicity of the copy operation. If an error occurs after the destination file
5144has been opened for writing, Node.js will attempt to remove the destination.
5145
5146`mode` is an optional integer that specifies the behavior
5147of the copy operation. It is possible to create a mask consisting of the bitwise
5148OR of two or more values (e.g.
5149`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
5150
5151* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
5152  exists.
5153* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
5154  copy-on-write reflink. If the platform does not support copy-on-write, then a
5155  fallback copy mechanism is used.
5156* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
5157  create a copy-on-write reflink. If the platform does not support
5158  copy-on-write, then the operation will fail.
5159
5160```mjs
5161import { copyFileSync, constants } from 'node:fs';
5162
5163// destination.txt will be created or overwritten by default.
5164copyFileSync('source.txt', 'destination.txt');
5165console.log('source.txt was copied to destination.txt');
5166
5167// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
5168copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
5169```
5170
5171### `fs.cpSync(src, dest[, options])`
5172
5173<!-- YAML
5174added: v16.7.0
5175changes:
5176  - version: v18.17.0
5177    pr-url: https://github.com/nodejs/node/pull/47084
5178    description: Accept an additional `mode` option to specify
5179                 the copy behavior as the `mode` argument of `fs.copyFile()`.
5180  - version: v17.6.0
5181    pr-url: https://github.com/nodejs/node/pull/41819
5182    description: Accepts an additional `verbatimSymlinks` option to specify
5183                 whether to perform path resolution for symlinks.
5184-->
5185
5186> Stability: 1 - Experimental
5187
5188* `src` {string|URL} source path to copy.
5189* `dest` {string|URL} destination path to copy to.
5190* `options` {Object}
5191  * `dereference` {boolean} dereference symlinks. **Default:** `false`.
5192  * `errorOnExist` {boolean} when `force` is `false`, and the destination
5193    exists, throw an error. **Default:** `false`.
5194  * `filter` {Function} Function to filter copied files/directories. Return
5195    `true` to copy the item, `false` to ignore it. When ignoring a directory,
5196    all of its contents will be skipped as well. **Default:** `undefined`
5197    * `src` {string} source path to copy.
5198    * `dest` {string} destination path to copy to.
5199    * Returns: {boolean}
5200  * `force` {boolean} overwrite existing file or directory. The copy
5201    operation will ignore errors if you set this to false and the destination
5202    exists. Use the `errorOnExist` option to change this behavior.
5203    **Default:** `true`.
5204  * `mode` {integer} modifiers for copy operation. **Default:** `0`.
5205    See `mode` flag of [`fs.copyFileSync()`][].
5206  * `preserveTimestamps` {boolean} When `true` timestamps from `src` will
5207    be preserved. **Default:** `false`.
5208  * `recursive` {boolean} copy directories recursively **Default:** `false`
5209  * `verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will
5210    be skipped. **Default:** `false`
5211
5212Synchronously copies the entire directory structure from `src` to `dest`,
5213including subdirectories and files.
5214
5215When copying a directory to another directory, globs are not supported and
5216behavior is similar to `cp dir1/ dir2/`.
5217
5218### `fs.existsSync(path)`
5219
5220<!-- YAML
5221added: v0.1.21
5222changes:
5223  - version: v7.6.0
5224    pr-url: https://github.com/nodejs/node/pull/10739
5225    description: The `path` parameter can be a WHATWG `URL` object using
5226                 `file:` protocol.
5227-->
5228
5229* `path` {string|Buffer|URL}
5230* Returns: {boolean}
5231
5232Returns `true` if the path exists, `false` otherwise.
5233
5234For detailed information, see the documentation of the asynchronous version of
5235this API: [`fs.exists()`][].
5236
5237`fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`
5238parameter to `fs.exists()` accepts parameters that are inconsistent with other
5239Node.js callbacks. `fs.existsSync()` does not use a callback.
5240
5241```mjs
5242import { existsSync } from 'node:fs';
5243
5244if (existsSync('/etc/passwd'))
5245  console.log('The path exists.');
5246```
5247
5248### `fs.fchmodSync(fd, mode)`
5249
5250<!-- YAML
5251added: v0.4.7
5252-->
5253
5254* `fd` {integer}
5255* `mode` {string|integer}
5256
5257Sets the permissions on the file. Returns `undefined`.
5258
5259See the POSIX fchmod(2) documentation for more detail.
5260
5261### `fs.fchownSync(fd, uid, gid)`
5262
5263<!-- YAML
5264added: v0.4.7
5265-->
5266
5267* `fd` {integer}
5268* `uid` {integer} The file's new owner's user id.
5269* `gid` {integer} The file's new group's group id.
5270
5271Sets the owner of the file. Returns `undefined`.
5272
5273See the POSIX fchown(2) documentation for more detail.
5274
5275### `fs.fdatasyncSync(fd)`
5276
5277<!-- YAML
5278added: v0.1.96
5279-->
5280
5281* `fd` {integer}
5282
5283Forces all currently queued I/O operations associated with the file to the
5284operating system's synchronized I/O completion state. Refer to the POSIX
5285fdatasync(2) documentation for details. Returns `undefined`.
5286
5287### `fs.fstatSync(fd[, options])`
5288
5289<!-- YAML
5290added: v0.1.95
5291changes:
5292  - version: v10.5.0
5293    pr-url: https://github.com/nodejs/node/pull/20220
5294    description: Accepts an additional `options` object to specify whether
5295                 the numeric values returned should be bigint.
5296-->
5297
5298* `fd` {integer}
5299* `options` {Object}
5300  * `bigint` {boolean} Whether the numeric values in the returned
5301    {fs.Stats} object should be `bigint`. **Default:** `false`.
5302* Returns: {fs.Stats}
5303
5304Retrieves the {fs.Stats} for the file descriptor.
5305
5306See the POSIX fstat(2) documentation for more detail.
5307
5308### `fs.fsyncSync(fd)`
5309
5310<!-- YAML
5311added: v0.1.96
5312-->
5313
5314* `fd` {integer}
5315
5316Request that all data for the open file descriptor is flushed to the storage
5317device. The specific implementation is operating system and device specific.
5318Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`.
5319
5320### `fs.ftruncateSync(fd[, len])`
5321
5322<!-- YAML
5323added: v0.8.6
5324-->
5325
5326* `fd` {integer}
5327* `len` {integer} **Default:** `0`
5328
5329Truncates the file descriptor. Returns `undefined`.
5330
5331For detailed information, see the documentation of the asynchronous version of
5332this API: [`fs.ftruncate()`][].
5333
5334### `fs.futimesSync(fd, atime, mtime)`
5335
5336<!-- YAML
5337added: v0.4.2
5338changes:
5339  - version: v4.1.0
5340    pr-url: https://github.com/nodejs/node/pull/2387
5341    description: Numeric strings, `NaN`, and `Infinity` are now allowed
5342                 time specifiers.
5343-->
5344
5345* `fd` {integer}
5346* `atime` {number|string|Date}
5347* `mtime` {number|string|Date}
5348
5349Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
5350
5351### `fs.lchmodSync(path, mode)`
5352
5353<!-- YAML
5354deprecated: v0.4.7
5355-->
5356
5357* `path` {string|Buffer|URL}
5358* `mode` {integer}
5359
5360Changes the permissions on a symbolic link. Returns `undefined`.
5361
5362This method is only implemented on macOS.
5363
5364See the POSIX lchmod(2) documentation for more detail.
5365
5366### `fs.lchownSync(path, uid, gid)`
5367
5368<!-- YAML
5369changes:
5370  - version: v10.6.0
5371    pr-url: https://github.com/nodejs/node/pull/21498
5372    description: This API is no longer deprecated.
5373  - version: v0.4.7
5374    description: Documentation-only deprecation.
5375-->
5376
5377* `path` {string|Buffer|URL}
5378* `uid` {integer} The file's new owner's user id.
5379* `gid` {integer} The file's new group's group id.
5380
5381Set the owner for the path. Returns `undefined`.
5382
5383See the POSIX lchown(2) documentation for more details.
5384
5385### `fs.lutimesSync(path, atime, mtime)`
5386
5387<!-- YAML
5388added:
5389  - v14.5.0
5390  - v12.19.0
5391-->
5392
5393* `path` {string|Buffer|URL}
5394* `atime` {number|string|Date}
5395* `mtime` {number|string|Date}
5396
5397Change the file system timestamps of the symbolic link referenced by `path`.
5398Returns `undefined`, or throws an exception when parameters are incorrect or
5399the operation fails. This is the synchronous version of [`fs.lutimes()`][].
5400
5401### `fs.linkSync(existingPath, newPath)`
5402
5403<!-- YAML
5404added: v0.1.31
5405changes:
5406  - version: v7.6.0
5407    pr-url: https://github.com/nodejs/node/pull/10739
5408    description: The `existingPath` and `newPath` parameters can be WHATWG
5409                 `URL` objects using `file:` protocol. Support is currently
5410                 still *experimental*.
5411-->
5412
5413* `existingPath` {string|Buffer|URL}
5414* `newPath` {string|Buffer|URL}
5415
5416Creates a new link from the `existingPath` to the `newPath`. See the POSIX
5417link(2) documentation for more detail. Returns `undefined`.
5418
5419### `fs.lstatSync(path[, options])`
5420
5421<!-- YAML
5422added: v0.1.30
5423changes:
5424  - version:
5425    - v15.3.0
5426    - v14.17.0
5427    pr-url: https://github.com/nodejs/node/pull/33716
5428    description: Accepts a `throwIfNoEntry` option to specify whether
5429                 an exception should be thrown if the entry does not exist.
5430  - version: v10.5.0
5431    pr-url: https://github.com/nodejs/node/pull/20220
5432    description: Accepts an additional `options` object to specify whether
5433                 the numeric values returned should be bigint.
5434  - version: v7.6.0
5435    pr-url: https://github.com/nodejs/node/pull/10739
5436    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5437                 protocol.
5438-->
5439
5440* `path` {string|Buffer|URL}
5441* `options` {Object}
5442  * `bigint` {boolean} Whether the numeric values in the returned
5443    {fs.Stats} object should be `bigint`. **Default:** `false`.
5444  * `throwIfNoEntry` {boolean} Whether an exception will be thrown
5445    if no file system entry exists, rather than returning `undefined`.
5446    **Default:** `true`.
5447* Returns: {fs.Stats}
5448
5449Retrieves the {fs.Stats} for the symbolic link referred to by `path`.
5450
5451See the POSIX lstat(2) documentation for more details.
5452
5453### `fs.mkdirSync(path[, options])`
5454
5455<!-- YAML
5456added: v0.1.21
5457changes:
5458  - version:
5459     - v13.11.0
5460     - v12.17.0
5461    pr-url: https://github.com/nodejs/node/pull/31530
5462    description: In `recursive` mode, the first created path is returned now.
5463  - version: v10.12.0
5464    pr-url: https://github.com/nodejs/node/pull/21875
5465    description: The second argument can now be an `options` object with
5466                 `recursive` and `mode` properties.
5467  - version: v7.6.0
5468    pr-url: https://github.com/nodejs/node/pull/10739
5469    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5470                 protocol.
5471-->
5472
5473* `path` {string|Buffer|URL}
5474* `options` {Object|integer}
5475  * `recursive` {boolean} **Default:** `false`
5476  * `mode` {string|integer} Not supported on Windows. **Default:** `0o777`.
5477* Returns: {string|undefined}
5478
5479Synchronously creates a directory. Returns `undefined`, or if `recursive` is
5480`true`, the first directory path created.
5481This is the synchronous version of [`fs.mkdir()`][].
5482
5483See the POSIX mkdir(2) documentation for more details.
5484
5485### `fs.mkdtempSync(prefix[, options])`
5486
5487<!-- YAML
5488added: v5.10.0
5489changes:
5490  - version: v18.19.0
5491    pr-url: https://github.com/nodejs/node/pull/48828
5492    description: The `prefix` parameter now accepts buffers and URL.
5493  - version:
5494      - v16.5.0
5495      - v14.18.0
5496    pr-url: https://github.com/nodejs/node/pull/39028
5497    description: The `prefix` parameter now accepts an empty string.
5498-->
5499
5500* `prefix` {string|Buffer|URL}
5501* `options` {string|Object}
5502  * `encoding` {string} **Default:** `'utf8'`
5503* Returns: {string}
5504
5505Returns the created directory path.
5506
5507For detailed information, see the documentation of the asynchronous version of
5508this API: [`fs.mkdtemp()`][].
5509
5510The optional `options` argument can be a string specifying an encoding, or an
5511object with an `encoding` property specifying the character encoding to use.
5512
5513### `fs.opendirSync(path[, options])`
5514
5515<!-- YAML
5516added: v12.12.0
5517changes:
5518  - version: v18.17.0
5519    pr-url: https://github.com/nodejs/node/pull/41439
5520    description: Added `recursive` option.
5521  - version:
5522     - v13.1.0
5523     - v12.16.0
5524    pr-url: https://github.com/nodejs/node/pull/30114
5525    description: The `bufferSize` option was introduced.
5526-->
5527
5528* `path` {string|Buffer|URL}
5529* `options` {Object}
5530  * `encoding` {string|null} **Default:** `'utf8'`
5531  * `bufferSize` {number} Number of directory entries that are buffered
5532    internally when reading from the directory. Higher values lead to better
5533    performance but higher memory usage. **Default:** `32`
5534  * `recursive` {boolean} **Default:** `false`
5535* Returns: {fs.Dir}
5536
5537Synchronously open a directory. See opendir(3).
5538
5539Creates an {fs.Dir}, which contains all further functions for reading from
5540and cleaning up the directory.
5541
5542The `encoding` option sets the encoding for the `path` while opening the
5543directory and subsequent read operations.
5544
5545### `fs.openSync(path[, flags[, mode]])`
5546
5547<!-- YAML
5548added: v0.1.21
5549changes:
5550  - version: v11.1.0
5551    pr-url: https://github.com/nodejs/node/pull/23767
5552    description: The `flags` argument is now optional and defaults to `'r'`.
5553  - version: v9.9.0
5554    pr-url: https://github.com/nodejs/node/pull/18801
5555    description: The `as` and `as+` flags are supported now.
5556  - version: v7.6.0
5557    pr-url: https://github.com/nodejs/node/pull/10739
5558    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5559                 protocol.
5560-->
5561
5562* `path` {string|Buffer|URL}
5563* `flags` {string|number} **Default:** `'r'`.
5564  See [support of file system `flags`][].
5565* `mode` {string|integer} **Default:** `0o666`
5566* Returns: {number}
5567
5568Returns an integer representing the file descriptor.
5569
5570For detailed information, see the documentation of the asynchronous version of
5571this API: [`fs.open()`][].
5572
5573### `fs.readdirSync(path[, options])`
5574
5575<!-- YAML
5576added: v0.1.21
5577changes:
5578  - version: v18.17.0
5579    pr-url: https://github.com/nodejs/node/pull/41439
5580    description: Added `recursive` option.
5581  - version: v10.10.0
5582    pr-url: https://github.com/nodejs/node/pull/22020
5583    description: New option `withFileTypes` was added.
5584  - version: v7.6.0
5585    pr-url: https://github.com/nodejs/node/pull/10739
5586    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5587                 protocol.
5588-->
5589
5590* `path` {string|Buffer|URL}
5591* `options` {string|Object}
5592  * `encoding` {string} **Default:** `'utf8'`
5593  * `withFileTypes` {boolean} **Default:** `false`
5594  * `recursive` {boolean} **Default:** `false`
5595* Returns: {string\[]|Buffer\[]|fs.Dirent\[]}
5596
5597Reads the contents of the directory.
5598
5599See the POSIX readdir(3) documentation for more details.
5600
5601The optional `options` argument can be a string specifying an encoding, or an
5602object with an `encoding` property specifying the character encoding to use for
5603the filenames returned. If the `encoding` is set to `'buffer'`,
5604the filenames returned will be passed as {Buffer} objects.
5605
5606If `options.withFileTypes` is set to `true`, the result will contain
5607{fs.Dirent} objects.
5608
5609### `fs.readFileSync(path[, options])`
5610
5611<!-- YAML
5612added: v0.1.8
5613changes:
5614  - version: v7.6.0
5615    pr-url: https://github.com/nodejs/node/pull/10739
5616    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5617                 protocol.
5618  - version: v5.0.0
5619    pr-url: https://github.com/nodejs/node/pull/3163
5620    description: The `path` parameter can be a file descriptor now.
5621-->
5622
5623* `path` {string|Buffer|URL|integer} filename or file descriptor
5624* `options` {Object|string}
5625  * `encoding` {string|null} **Default:** `null`
5626  * `flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.
5627* Returns: {string|Buffer}
5628
5629Returns the contents of the `path`.
5630
5631For detailed information, see the documentation of the asynchronous version of
5632this API: [`fs.readFile()`][].
5633
5634If the `encoding` option is specified then this function returns a
5635string. Otherwise it returns a buffer.
5636
5637Similar to [`fs.readFile()`][], when the path is a directory, the behavior of
5638`fs.readFileSync()` is platform-specific.
5639
5640```mjs
5641import { readFileSync } from 'node:fs';
5642
5643// macOS, Linux, and Windows
5644readFileSync('<directory>');
5645// => [Error: EISDIR: illegal operation on a directory, read <directory>]
5646
5647//  FreeBSD
5648readFileSync('<directory>'); // => <data>
5649```
5650
5651### `fs.readlinkSync(path[, options])`
5652
5653<!-- YAML
5654added: v0.1.31
5655changes:
5656  - version: v7.6.0
5657    pr-url: https://github.com/nodejs/node/pull/10739
5658    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5659                 protocol.
5660-->
5661
5662* `path` {string|Buffer|URL}
5663* `options` {string|Object}
5664  * `encoding` {string} **Default:** `'utf8'`
5665* Returns: {string|Buffer}
5666
5667Returns the symbolic link's string value.
5668
5669See the POSIX readlink(2) documentation for more details.
5670
5671The optional `options` argument can be a string specifying an encoding, or an
5672object with an `encoding` property specifying the character encoding to use for
5673the link path returned. If the `encoding` is set to `'buffer'`,
5674the link path returned will be passed as a {Buffer} object.
5675
5676### `fs.readSync(fd, buffer, offset, length[, position])`
5677
5678<!-- YAML
5679added: v0.1.21
5680changes:
5681  - version: v10.10.0
5682    pr-url: https://github.com/nodejs/node/pull/22150
5683    description: The `buffer` parameter can now be any `TypedArray` or a
5684                 `DataView`.
5685  - version: v6.0.0
5686    pr-url: https://github.com/nodejs/node/pull/4518
5687    description: The `length` parameter can now be `0`.
5688-->
5689
5690* `fd` {integer}
5691* `buffer` {Buffer|TypedArray|DataView}
5692* `offset` {integer}
5693* `length` {integer}
5694* `position` {integer|bigint|null} **Default:** `null`
5695* Returns: {number}
5696
5697Returns the number of `bytesRead`.
5698
5699For detailed information, see the documentation of the asynchronous version of
5700this API: [`fs.read()`][].
5701
5702### `fs.readSync(fd, buffer[, options])`
5703
5704<!-- YAML
5705added:
5706 - v13.13.0
5707 - v12.17.0
5708changes:
5709  - version:
5710     - v13.13.0
5711     - v12.17.0
5712    pr-url: https://github.com/nodejs/node/pull/32460
5713    description: Options object can be passed in
5714                 to make offset, length, and position optional.
5715-->
5716
5717* `fd` {integer}
5718* `buffer` {Buffer|TypedArray|DataView}
5719* `options` {Object}
5720  * `offset` {integer} **Default:** `0`
5721  * `length` {integer} **Default:** `buffer.byteLength - offset`
5722  * `position` {integer|bigint|null} **Default:** `null`
5723* Returns: {number}
5724
5725Returns the number of `bytesRead`.
5726
5727Similar to the above `fs.readSync` function, this version takes an optional `options` object.
5728If no `options` object is specified, it will default with the above values.
5729
5730For detailed information, see the documentation of the asynchronous version of
5731this API: [`fs.read()`][].
5732
5733### `fs.readvSync(fd, buffers[, position])`
5734
5735<!-- YAML
5736added:
5737 - v13.13.0
5738 - v12.17.0
5739-->
5740
5741* `fd` {integer}
5742* `buffers` {ArrayBufferView\[]}
5743* `position` {integer|null} **Default:** `null`
5744* Returns: {number} The number of bytes read.
5745
5746For detailed information, see the documentation of the asynchronous version of
5747this API: [`fs.readv()`][].
5748
5749### `fs.realpathSync(path[, options])`
5750
5751<!-- YAML
5752added: v0.1.31
5753changes:
5754  - version: v8.0.0
5755    pr-url: https://github.com/nodejs/node/pull/13028
5756    description: Pipe/Socket resolve support was added.
5757  - version: v7.6.0
5758    pr-url: https://github.com/nodejs/node/pull/10739
5759    description: The `path` parameter can be a WHATWG `URL` object using
5760                 `file:` protocol.
5761  - version: v6.4.0
5762    pr-url: https://github.com/nodejs/node/pull/7899
5763    description: Calling `realpathSync` now works again for various edge cases
5764                 on Windows.
5765  - version: v6.0.0
5766    pr-url: https://github.com/nodejs/node/pull/3594
5767    description: The `cache` parameter was removed.
5768-->
5769
5770* `path` {string|Buffer|URL}
5771* `options` {string|Object}
5772  * `encoding` {string} **Default:** `'utf8'`
5773* Returns: {string|Buffer}
5774
5775Returns the resolved pathname.
5776
5777For detailed information, see the documentation of the asynchronous version of
5778this API: [`fs.realpath()`][].
5779
5780### `fs.realpathSync.native(path[, options])`
5781
5782<!-- YAML
5783added: v9.2.0
5784-->
5785
5786* `path` {string|Buffer|URL}
5787* `options` {string|Object}
5788  * `encoding` {string} **Default:** `'utf8'`
5789* Returns: {string|Buffer}
5790
5791Synchronous realpath(3).
5792
5793Only paths that can be converted to UTF8 strings are supported.
5794
5795The optional `options` argument can be a string specifying an encoding, or an
5796object with an `encoding` property specifying the character encoding to use for
5797the path returned. If the `encoding` is set to `'buffer'`,
5798the path returned will be passed as a {Buffer} object.
5799
5800On Linux, when Node.js is linked against musl libc, the procfs file system must
5801be mounted on `/proc` in order for this function to work. Glibc does not have
5802this restriction.
5803
5804### `fs.renameSync(oldPath, newPath)`
5805
5806<!-- YAML
5807added: v0.1.21
5808changes:
5809  - version: v7.6.0
5810    pr-url: https://github.com/nodejs/node/pull/10739
5811    description: The `oldPath` and `newPath` parameters can be WHATWG `URL`
5812                 objects using `file:` protocol. Support is currently still
5813                 *experimental*.
5814-->
5815
5816* `oldPath` {string|Buffer|URL}
5817* `newPath` {string|Buffer|URL}
5818
5819Renames the file from `oldPath` to `newPath`. Returns `undefined`.
5820
5821See the POSIX rename(2) documentation for more details.
5822
5823### `fs.rmdirSync(path[, options])`
5824
5825<!-- YAML
5826added: v0.1.21
5827changes:
5828  - version: v16.0.0
5829    pr-url: https://github.com/nodejs/node/pull/37216
5830    description: "Using `fs.rmdirSync(path, { recursive: true })` on a `path`
5831                 that is a file is no longer permitted and results in an
5832                 `ENOENT` error on Windows and an `ENOTDIR` error on POSIX."
5833  - version: v16.0.0
5834    pr-url: https://github.com/nodejs/node/pull/37216
5835    description: "Using `fs.rmdirSync(path, { recursive: true })` on a `path`
5836                 that does not exist is no longer permitted and results in a
5837                 `ENOENT` error."
5838  - version: v16.0.0
5839    pr-url: https://github.com/nodejs/node/pull/37302
5840    description: The `recursive` option is deprecated, using it triggers a
5841                 deprecation warning.
5842  - version: v14.14.0
5843    pr-url: https://github.com/nodejs/node/pull/35579
5844    description: The `recursive` option is deprecated, use `fs.rmSync` instead.
5845  - version:
5846     - v13.3.0
5847     - v12.16.0
5848    pr-url: https://github.com/nodejs/node/pull/30644
5849    description: The `maxBusyTries` option is renamed to `maxRetries`, and its
5850                 default is 0. The `emfileWait` option has been removed, and
5851                 `EMFILE` errors use the same retry logic as other errors. The
5852                 `retryDelay` option is now supported. `ENFILE` errors are now
5853                 retried.
5854  - version: v12.10.0
5855    pr-url: https://github.com/nodejs/node/pull/29168
5856    description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
5857                 now supported.
5858  - version: v7.6.0
5859    pr-url: https://github.com/nodejs/node/pull/10739
5860    description: The `path` parameters can be a WHATWG `URL` object using
5861                 `file:` protocol.
5862-->
5863
5864* `path` {string|Buffer|URL}
5865* `options` {Object}
5866  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
5867    `EPERM` error is encountered, Node.js retries the operation with a linear
5868    backoff wait of `retryDelay` milliseconds longer on each try. This option
5869    represents the number of retries. This option is ignored if the `recursive`
5870    option is not `true`. **Default:** `0`.
5871  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
5872    recursive mode, operations are retried on failure. **Default:** `false`.
5873    **Deprecated.**
5874  * `retryDelay` {integer} The amount of time in milliseconds to wait between
5875    retries. This option is ignored if the `recursive` option is not `true`.
5876    **Default:** `100`.
5877
5878Synchronous rmdir(2). Returns `undefined`.
5879
5880Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
5881on Windows and an `ENOTDIR` error on POSIX.
5882
5883To get a behavior similar to the `rm -rf` Unix command, use [`fs.rmSync()`][]
5884with options `{ recursive: true, force: true }`.
5885
5886### `fs.rmSync(path[, options])`
5887
5888<!-- YAML
5889added: v14.14.0
5890changes:
5891  - version:
5892      - v17.3.0
5893      - v16.14.0
5894    pr-url: https://github.com/nodejs/node/pull/41132
5895    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5896                 protocol.
5897-->
5898
5899* `path` {string|Buffer|URL}
5900* `options` {Object}
5901  * `force` {boolean} When `true`, exceptions will be ignored if `path` does
5902    not exist. **Default:** `false`.
5903  * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
5904    `EPERM` error is encountered, Node.js will retry the operation with a linear
5905    backoff wait of `retryDelay` milliseconds longer on each try. This option
5906    represents the number of retries. This option is ignored if the `recursive`
5907    option is not `true`. **Default:** `0`.
5908  * `recursive` {boolean} If `true`, perform a recursive directory removal. In
5909    recursive mode operations are retried on failure. **Default:** `false`.
5910  * `retryDelay` {integer} The amount of time in milliseconds to wait between
5911    retries. This option is ignored if the `recursive` option is not `true`.
5912    **Default:** `100`.
5913
5914Synchronously removes files and directories (modeled on the standard POSIX `rm`
5915utility). Returns `undefined`.
5916
5917### `fs.statSync(path[, options])`
5918
5919<!-- YAML
5920added: v0.1.21
5921changes:
5922  - version:
5923    - v15.3.0
5924    - v14.17.0
5925    pr-url: https://github.com/nodejs/node/pull/33716
5926    description: Accepts a `throwIfNoEntry` option to specify whether
5927                 an exception should be thrown if the entry does not exist.
5928  - version: v10.5.0
5929    pr-url: https://github.com/nodejs/node/pull/20220
5930    description: Accepts an additional `options` object to specify whether
5931                 the numeric values returned should be bigint.
5932  - version: v7.6.0
5933    pr-url: https://github.com/nodejs/node/pull/10739
5934    description: The `path` parameter can be a WHATWG `URL` object using `file:`
5935                 protocol.
5936-->
5937
5938* `path` {string|Buffer|URL}
5939* `options` {Object}
5940  * `bigint` {boolean} Whether the numeric values in the returned
5941    {fs.Stats} object should be `bigint`. **Default:** `false`.
5942  * `throwIfNoEntry` {boolean} Whether an exception will be thrown
5943    if no file system entry exists, rather than returning `undefined`.
5944    **Default:** `true`.
5945* Returns: {fs.Stats}
5946
5947Retrieves the {fs.Stats} for the path.
5948
5949### `fs.statfsSync(path[, options])`
5950
5951<!-- YAML
5952added: v18.15.0
5953-->
5954
5955* `path` {string|Buffer|URL}
5956* `options` {Object}
5957  * `bigint` {boolean} Whether the numeric values in the returned
5958    {fs.StatFs} object should be `bigint`. **Default:** `false`.
5959* Returns: {fs.StatFs}
5960
5961Synchronous statfs(2). Returns information about the mounted file system which
5962contains `path`.
5963
5964In case of an error, the `err.code` will be one of [Common System Errors][].
5965
5966### `fs.symlinkSync(target, path[, type])`
5967
5968<!-- YAML
5969added: v0.1.31
5970changes:
5971  - version: v12.0.0
5972    pr-url: https://github.com/nodejs/node/pull/23724
5973    description: If the `type` argument is left undefined, Node will autodetect
5974                 `target` type and automatically select `dir` or `file`.
5975  - version: v7.6.0
5976    pr-url: https://github.com/nodejs/node/pull/10739
5977    description: The `target` and `path` parameters can be WHATWG `URL` objects
5978                 using `file:` protocol. Support is currently still
5979                 *experimental*.
5980-->
5981
5982* `target` {string|Buffer|URL}
5983* `path` {string|Buffer|URL}
5984* `type` {string|null} **Default:** `null`
5985
5986Returns `undefined`.
5987
5988For detailed information, see the documentation of the asynchronous version of
5989this API: [`fs.symlink()`][].
5990
5991### `fs.truncateSync(path[, len])`
5992
5993<!-- YAML
5994added: v0.8.6
5995-->
5996
5997* `path` {string|Buffer|URL}
5998* `len` {integer} **Default:** `0`
5999
6000Truncates the file. Returns `undefined`. A file descriptor can also be
6001passed as the first argument. In this case, `fs.ftruncateSync()` is called.
6002
6003Passing a file descriptor is deprecated and may result in an error being thrown
6004in the future.
6005
6006### `fs.unlinkSync(path)`
6007
6008<!-- YAML
6009added: v0.1.21
6010changes:
6011  - version: v7.6.0
6012    pr-url: https://github.com/nodejs/node/pull/10739
6013    description: The `path` parameter can be a WHATWG `URL` object using `file:`
6014                 protocol.
6015-->
6016
6017* `path` {string|Buffer|URL}
6018
6019Synchronous unlink(2). Returns `undefined`.
6020
6021### `fs.utimesSync(path, atime, mtime)`
6022
6023<!-- YAML
6024added: v0.4.2
6025changes:
6026  - version: v8.0.0
6027    pr-url: https://github.com/nodejs/node/pull/11919
6028    description: "`NaN`, `Infinity`, and `-Infinity` are no longer valid time
6029                 specifiers."
6030  - version: v7.6.0
6031    pr-url: https://github.com/nodejs/node/pull/10739
6032    description: The `path` parameter can be a WHATWG `URL` object using `file:`
6033                 protocol.
6034  - version: v4.1.0
6035    pr-url: https://github.com/nodejs/node/pull/2387
6036    description: Numeric strings, `NaN`, and `Infinity` are now allowed
6037                 time specifiers.
6038-->
6039
6040* `path` {string|Buffer|URL}
6041* `atime` {number|string|Date}
6042* `mtime` {number|string|Date}
6043
6044Returns `undefined`.
6045
6046For detailed information, see the documentation of the asynchronous version of
6047this API: [`fs.utimes()`][].
6048
6049### `fs.writeFileSync(file, data[, options])`
6050
6051<!-- YAML
6052added: v0.1.29
6053changes:
6054  - version: v17.8.0
6055    pr-url: https://github.com/nodejs/node/pull/42149
6056    description: Passing to the `data` parameter an object with an own
6057                 `toString` function is deprecated.
6058  - version: v14.12.0
6059    pr-url: https://github.com/nodejs/node/pull/34993
6060    description: The `data` parameter will stringify an object with an
6061                 explicit `toString` function.
6062  - version: v14.0.0
6063    pr-url: https://github.com/nodejs/node/pull/31030
6064    description: The `data` parameter won't coerce unsupported input to
6065                 strings anymore.
6066  - version: v10.10.0
6067    pr-url: https://github.com/nodejs/node/pull/22150
6068    description: The `data` parameter can now be any `TypedArray` or a
6069                 `DataView`.
6070  - version: v7.4.0
6071    pr-url: https://github.com/nodejs/node/pull/10382
6072    description: The `data` parameter can now be a `Uint8Array`.
6073  - version: v5.0.0
6074    pr-url: https://github.com/nodejs/node/pull/3163
6075    description: The `file` parameter can be a file descriptor now.
6076-->
6077
6078* `file` {string|Buffer|URL|integer} filename or file descriptor
6079* `data` {string|Buffer|TypedArray|DataView|Object}
6080* `options` {Object|string}
6081  * `encoding` {string|null} **Default:** `'utf8'`
6082  * `mode` {integer} **Default:** `0o666`
6083  * `flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.
6084
6085Returns `undefined`.
6086
6087The `mode` option only affects the newly created file. See [`fs.open()`][]
6088for more details.
6089
6090For detailed information, see the documentation of the asynchronous version of
6091this API: [`fs.writeFile()`][].
6092
6093### `fs.writeSync(fd, buffer, offset[, length[, position]])`
6094
6095<!-- YAML
6096added: v0.1.21
6097changes:
6098  - version: v14.0.0
6099    pr-url: https://github.com/nodejs/node/pull/31030
6100    description: The `buffer` parameter won't coerce unsupported input to
6101                 strings anymore.
6102  - version: v10.10.0
6103    pr-url: https://github.com/nodejs/node/pull/22150
6104    description: The `buffer` parameter can now be any `TypedArray` or a
6105                 `DataView`.
6106  - version: v7.4.0
6107    pr-url: https://github.com/nodejs/node/pull/10382
6108    description: The `buffer` parameter can now be a `Uint8Array`.
6109  - version: v7.2.0
6110    pr-url: https://github.com/nodejs/node/pull/7856
6111    description: The `offset` and `length` parameters are optional now.
6112-->
6113
6114* `fd` {integer}
6115* `buffer` {Buffer|TypedArray|DataView}
6116* `offset` {integer} **Default:** `0`
6117* `length` {integer} **Default:** `buffer.byteLength - offset`
6118* `position` {integer|null} **Default:** `null`
6119* Returns: {number} The number of bytes written.
6120
6121For detailed information, see the documentation of the asynchronous version of
6122this API: [`fs.write(fd, buffer...)`][].
6123
6124### `fs.writeSync(fd, buffer[, options])`
6125
6126<!-- YAML
6127added: v18.3.0
6128-->
6129
6130* `fd` {integer}
6131* `buffer` {Buffer|TypedArray|DataView}
6132* `options` {Object}
6133  * `offset` {integer} **Default:** `0`
6134  * `length` {integer} **Default:** `buffer.byteLength - offset`
6135  * `position` {integer} **Default:** `null`
6136* Returns: {number} The number of bytes written.
6137
6138For detailed information, see the documentation of the asynchronous version of
6139this API: [`fs.write(fd, buffer...)`][].
6140
6141### `fs.writeSync(fd, string[, position[, encoding]])`
6142
6143<!-- YAML
6144added: v0.11.5
6145changes:
6146  - version: v14.0.0
6147    pr-url: https://github.com/nodejs/node/pull/31030
6148    description: The `string` parameter won't coerce unsupported input to
6149                 strings anymore.
6150  - version: v7.2.0
6151    pr-url: https://github.com/nodejs/node/pull/7856
6152    description: The `position` parameter is optional now.
6153-->
6154
6155* `fd` {integer}
6156* `string` {string}
6157* `position` {integer|null} **Default:** `null`
6158* `encoding` {string} **Default:** `'utf8'`
6159* Returns: {number} The number of bytes written.
6160
6161For detailed information, see the documentation of the asynchronous version of
6162this API: [`fs.write(fd, string...)`][].
6163
6164### `fs.writevSync(fd, buffers[, position])`
6165
6166<!-- YAML
6167added: v12.9.0
6168-->
6169
6170* `fd` {integer}
6171* `buffers` {ArrayBufferView\[]}
6172* `position` {integer|null} **Default:** `null`
6173* Returns: {number} The number of bytes written.
6174
6175For detailed information, see the documentation of the asynchronous version of
6176this API: [`fs.writev()`][].
6177
6178## Common Objects
6179
6180The common objects are shared by all of the file system API variants
6181(promise, callback, and synchronous).
6182
6183### Class: `fs.Dir`
6184
6185<!-- YAML
6186added: v12.12.0
6187-->
6188
6189A class representing a directory stream.
6190
6191Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or
6192[`fsPromises.opendir()`][].
6193
6194```mjs
6195import { opendir } from 'node:fs/promises';
6196
6197try {
6198  const dir = await opendir('./');
6199  for await (const dirent of dir)
6200    console.log(dirent.name);
6201} catch (err) {
6202  console.error(err);
6203}
6204```
6205
6206When using the async iterator, the {fs.Dir} object will be automatically
6207closed after the iterator exits.
6208
6209#### `dir.close()`
6210
6211<!-- YAML
6212added: v12.12.0
6213-->
6214
6215* Returns: {Promise}
6216
6217Asynchronously close the directory's underlying resource handle.
6218Subsequent reads will result in errors.
6219
6220A promise is returned that will be resolved after the resource has been
6221closed.
6222
6223#### `dir.close(callback)`
6224
6225<!-- YAML
6226added: v12.12.0
6227changes:
6228  - version: v18.0.0
6229    pr-url: https://github.com/nodejs/node/pull/41678
6230    description: Passing an invalid callback to the `callback` argument
6231                 now throws `ERR_INVALID_ARG_TYPE` instead of
6232                 `ERR_INVALID_CALLBACK`.
6233-->
6234
6235* `callback` {Function}
6236  * `err` {Error}
6237
6238Asynchronously close the directory's underlying resource handle.
6239Subsequent reads will result in errors.
6240
6241The `callback` will be called after the resource handle has been closed.
6242
6243#### `dir.closeSync()`
6244
6245<!-- YAML
6246added: v12.12.0
6247-->
6248
6249Synchronously close the directory's underlying resource handle.
6250Subsequent reads will result in errors.
6251
6252#### `dir.path`
6253
6254<!-- YAML
6255added: v12.12.0
6256-->
6257
6258* {string}
6259
6260The read-only path of this directory as was provided to [`fs.opendir()`][],
6261[`fs.opendirSync()`][], or [`fsPromises.opendir()`][].
6262
6263#### `dir.read()`
6264
6265<!-- YAML
6266added: v12.12.0
6267-->
6268
6269* Returns: {Promise} containing {fs.Dirent|null}
6270
6271Asynchronously read the next directory entry via readdir(3) as an
6272{fs.Dirent}.
6273
6274A promise is returned that will be resolved with an {fs.Dirent}, or `null`
6275if there are no more directory entries to read.
6276
6277Directory entries returned by this function are in no particular order as
6278provided by the operating system's underlying directory mechanisms.
6279Entries added or removed while iterating over the directory might not be
6280included in the iteration results.
6281
6282#### `dir.read(callback)`
6283
6284<!-- YAML
6285added: v12.12.0
6286-->
6287
6288* `callback` {Function}
6289  * `err` {Error}
6290  * `dirent` {fs.Dirent|null}
6291
6292Asynchronously read the next directory entry via readdir(3) as an
6293{fs.Dirent}.
6294
6295After the read is completed, the `callback` will be called with an
6296{fs.Dirent}, or `null` if there are no more directory entries to read.
6297
6298Directory entries returned by this function are in no particular order as
6299provided by the operating system's underlying directory mechanisms.
6300Entries added or removed while iterating over the directory might not be
6301included in the iteration results.
6302
6303#### `dir.readSync()`
6304
6305<!-- YAML
6306added: v12.12.0
6307-->
6308
6309* Returns: {fs.Dirent|null}
6310
6311Synchronously read the next directory entry as an {fs.Dirent}. See the
6312POSIX readdir(3) documentation for more detail.
6313
6314If there are no more directory entries to read, `null` will be returned.
6315
6316Directory entries returned by this function are in no particular order as
6317provided by the operating system's underlying directory mechanisms.
6318Entries added or removed while iterating over the directory might not be
6319included in the iteration results.
6320
6321#### `dir[Symbol.asyncIterator]()`
6322
6323<!-- YAML
6324added: v12.12.0
6325-->
6326
6327* Returns: {AsyncIterator} of {fs.Dirent}
6328
6329Asynchronously iterates over the directory until all entries have
6330been read. Refer to the POSIX readdir(3) documentation for more detail.
6331
6332Entries returned by the async iterator are always an {fs.Dirent}.
6333The `null` case from `dir.read()` is handled internally.
6334
6335See {fs.Dir} for an example.
6336
6337Directory entries returned by this iterator are in no particular order as
6338provided by the operating system's underlying directory mechanisms.
6339Entries added or removed while iterating over the directory might not be
6340included in the iteration results.
6341
6342### Class: `fs.Dirent`
6343
6344<!-- YAML
6345added: v10.10.0
6346-->
6347
6348A representation of a directory entry, which can be a file or a subdirectory
6349within the directory, as returned by reading from an {fs.Dir}. The
6350directory entry is a combination of the file name and file type pairs.
6351
6352Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with
6353the `withFileTypes` option set to `true`, the resulting array is filled with
6354{fs.Dirent} objects, rather than strings or {Buffer}s.
6355
6356#### `dirent.isBlockDevice()`
6357
6358<!-- YAML
6359added: v10.10.0
6360-->
6361
6362* Returns: {boolean}
6363
6364Returns `true` if the {fs.Dirent} object describes a block device.
6365
6366#### `dirent.isCharacterDevice()`
6367
6368<!-- YAML
6369added: v10.10.0
6370-->
6371
6372* Returns: {boolean}
6373
6374Returns `true` if the {fs.Dirent} object describes a character device.
6375
6376#### `dirent.isDirectory()`
6377
6378<!-- YAML
6379added: v10.10.0
6380-->
6381
6382* Returns: {boolean}
6383
6384Returns `true` if the {fs.Dirent} object describes a file system
6385directory.
6386
6387#### `dirent.isFIFO()`
6388
6389<!-- YAML
6390added: v10.10.0
6391-->
6392
6393* Returns: {boolean}
6394
6395Returns `true` if the {fs.Dirent} object describes a first-in-first-out
6396(FIFO) pipe.
6397
6398#### `dirent.isFile()`
6399
6400<!-- YAML
6401added: v10.10.0
6402-->
6403
6404* Returns: {boolean}
6405
6406Returns `true` if the {fs.Dirent} object describes a regular file.
6407
6408#### `dirent.isSocket()`
6409
6410<!-- YAML
6411added: v10.10.0
6412-->
6413
6414* Returns: {boolean}
6415
6416Returns `true` if the {fs.Dirent} object describes a socket.
6417
6418#### `dirent.isSymbolicLink()`
6419
6420<!-- YAML
6421added: v10.10.0
6422-->
6423
6424* Returns: {boolean}
6425
6426Returns `true` if the {fs.Dirent} object describes a symbolic link.
6427
6428#### `dirent.name`
6429
6430<!-- YAML
6431added: v10.10.0
6432-->
6433
6434* {string|Buffer}
6435
6436The file name that this {fs.Dirent} object refers to. The type of this
6437value is determined by the `options.encoding` passed to [`fs.readdir()`][] or
6438[`fs.readdirSync()`][].
6439
6440#### `dirent.parentPath`
6441
6442<!-- YAML
6443added:
6444  - v18.20.0
6445-->
6446
6447> Stability: 1 – Experimental
6448
6449* {string}
6450
6451The path to the parent directory of the file this {fs.Dirent} object refers to.
6452
6453#### `dirent.path`
6454
6455<!-- YAML
6456added: v18.17.0
6457deprecated: v18.20.0
6458-->
6459
6460> Stability: 0 - Deprecated: Use [`dirent.parentPath`][] instead.
6461
6462* {string}
6463
6464The base path that this {fs.Dirent} object refers to.
6465
6466### Class: `fs.FSWatcher`
6467
6468<!-- YAML
6469added: v0.5.8
6470-->
6471
6472* Extends {EventEmitter}
6473
6474A successful call to [`fs.watch()`][] method will return a new {fs.FSWatcher}
6475object.
6476
6477All {fs.FSWatcher} objects emit a `'change'` event whenever a specific watched
6478file is modified.
6479
6480#### Event: `'change'`
6481
6482<!-- YAML
6483added: v0.5.8
6484-->
6485
6486* `eventType` {string} The type of change event that has occurred
6487* `filename` {string|Buffer} The filename that changed (if relevant/available)
6488
6489Emitted when something changes in a watched directory or file.
6490See more details in [`fs.watch()`][].
6491
6492The `filename` argument may not be provided depending on operating system
6493support. If `filename` is provided, it will be provided as a {Buffer} if
6494`fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise
6495`filename` will be a UTF-8 string.
6496
6497```mjs
6498import { watch } from 'node:fs';
6499// Example when handled through fs.watch() listener
6500watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
6501  if (filename) {
6502    console.log(filename);
6503    // Prints: <Buffer ...>
6504  }
6505});
6506```
6507
6508#### Event: `'close'`
6509
6510<!-- YAML
6511added: v10.0.0
6512-->
6513
6514Emitted when the watcher stops watching for changes. The closed
6515{fs.FSWatcher} object is no longer usable in the event handler.
6516
6517#### Event: `'error'`
6518
6519<!-- YAML
6520added: v0.5.8
6521-->
6522
6523* `error` {Error}
6524
6525Emitted when an error occurs while watching the file. The errored
6526{fs.FSWatcher} object is no longer usable in the event handler.
6527
6528#### `watcher.close()`
6529
6530<!-- YAML
6531added: v0.5.8
6532-->
6533
6534Stop watching for changes on the given {fs.FSWatcher}. Once stopped, the
6535{fs.FSWatcher} object is no longer usable.
6536
6537#### `watcher.ref()`
6538
6539<!-- YAML
6540added:
6541  - v14.3.0
6542  - v12.20.0
6543-->
6544
6545* Returns: {fs.FSWatcher}
6546
6547When called, requests that the Node.js event loop _not_ exit so long as the
6548{fs.FSWatcher} is active. Calling `watcher.ref()` multiple times will have
6549no effect.
6550
6551By default, all {fs.FSWatcher} objects are "ref'ed", making it normally
6552unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
6553called previously.
6554
6555#### `watcher.unref()`
6556
6557<!-- YAML
6558added:
6559  - v14.3.0
6560  - v12.20.0
6561-->
6562
6563* Returns: {fs.FSWatcher}
6564
6565When called, the active {fs.FSWatcher} object will not require the Node.js
6566event loop to remain active. If there is no other activity keeping the
6567event loop running, the process may exit before the {fs.FSWatcher} object's
6568callback is invoked. Calling `watcher.unref()` multiple times will have
6569no effect.
6570
6571### Class: `fs.StatWatcher`
6572
6573<!-- YAML
6574added:
6575  - v14.3.0
6576  - v12.20.0
6577-->
6578
6579* Extends {EventEmitter}
6580
6581A successful call to `fs.watchFile()` method will return a new {fs.StatWatcher}
6582object.
6583
6584#### `watcher.ref()`
6585
6586<!-- YAML
6587added:
6588  - v14.3.0
6589  - v12.20.0
6590-->
6591
6592* Returns: {fs.StatWatcher}
6593
6594When called, requests that the Node.js event loop _not_ exit so long as the
6595{fs.StatWatcher} is active. Calling `watcher.ref()` multiple times will have
6596no effect.
6597
6598By default, all {fs.StatWatcher} objects are "ref'ed", making it normally
6599unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
6600called previously.
6601
6602#### `watcher.unref()`
6603
6604<!-- YAML
6605added:
6606  - v14.3.0
6607  - v12.20.0
6608-->
6609
6610* Returns: {fs.StatWatcher}
6611
6612When called, the active {fs.StatWatcher} object will not require the Node.js
6613event loop to remain active. If there is no other activity keeping the
6614event loop running, the process may exit before the {fs.StatWatcher} object's
6615callback is invoked. Calling `watcher.unref()` multiple times will have
6616no effect.
6617
6618### Class: `fs.ReadStream`
6619
6620<!-- YAML
6621added: v0.1.93
6622-->
6623
6624* Extends: {stream.Readable}
6625
6626Instances of {fs.ReadStream} are created and returned using the
6627[`fs.createReadStream()`][] function.
6628
6629#### Event: `'close'`
6630
6631<!-- YAML
6632added: v0.1.93
6633-->
6634
6635Emitted when the {fs.ReadStream}'s underlying file descriptor has been closed.
6636
6637#### Event: `'open'`
6638
6639<!-- YAML
6640added: v0.1.93
6641-->
6642
6643* `fd` {integer} Integer file descriptor used by the {fs.ReadStream}.
6644
6645Emitted when the {fs.ReadStream}'s file descriptor has been opened.
6646
6647#### Event: `'ready'`
6648
6649<!-- YAML
6650added: v9.11.0
6651-->
6652
6653Emitted when the {fs.ReadStream} is ready to be used.
6654
6655Fires immediately after `'open'`.
6656
6657#### `readStream.bytesRead`
6658
6659<!-- YAML
6660added: v6.4.0
6661-->
6662
6663* {number}
6664
6665The number of bytes that have been read so far.
6666
6667#### `readStream.path`
6668
6669<!-- YAML
6670added: v0.1.93
6671-->
6672
6673* {string|Buffer}
6674
6675The path to the file the stream is reading from as specified in the first
6676argument to `fs.createReadStream()`. If `path` is passed as a string, then
6677`readStream.path` will be a string. If `path` is passed as a {Buffer}, then
6678`readStream.path` will be a {Buffer}. If `fd` is specified, then
6679`readStream.path` will be `undefined`.
6680
6681#### `readStream.pending`
6682
6683<!-- YAML
6684added:
6685 - v11.2.0
6686 - v10.16.0
6687-->
6688
6689* {boolean}
6690
6691This property is `true` if the underlying file has not been opened yet,
6692i.e. before the `'ready'` event is emitted.
6693
6694### Class: `fs.Stats`
6695
6696<!-- YAML
6697added: v0.1.21
6698changes:
6699  - version: v8.1.0
6700    pr-url: https://github.com/nodejs/node/pull/13173
6701    description: Added times as numbers.
6702-->
6703
6704A {fs.Stats} object provides information about a file.
6705
6706Objects returned from [`fs.stat()`][], [`fs.lstat()`][], [`fs.fstat()`][], and
6707their synchronous counterparts are of this type.
6708If `bigint` in the `options` passed to those methods is true, the numeric values
6709will be `bigint` instead of `number`, and the object will contain additional
6710nanosecond-precision properties suffixed with `Ns`.
6711
6712```console
6713Stats {
6714  dev: 2114,
6715  ino: 48064969,
6716  mode: 33188,
6717  nlink: 1,
6718  uid: 85,
6719  gid: 100,
6720  rdev: 0,
6721  size: 527,
6722  blksize: 4096,
6723  blocks: 8,
6724  atimeMs: 1318289051000.1,
6725  mtimeMs: 1318289051000.1,
6726  ctimeMs: 1318289051000.1,
6727  birthtimeMs: 1318289051000.1,
6728  atime: Mon, 10 Oct 2011 23:24:11 GMT,
6729  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
6730  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
6731  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
6732```
6733
6734`bigint` version:
6735
6736```console
6737BigIntStats {
6738  dev: 2114n,
6739  ino: 48064969n,
6740  mode: 33188n,
6741  nlink: 1n,
6742  uid: 85n,
6743  gid: 100n,
6744  rdev: 0n,
6745  size: 527n,
6746  blksize: 4096n,
6747  blocks: 8n,
6748  atimeMs: 1318289051000n,
6749  mtimeMs: 1318289051000n,
6750  ctimeMs: 1318289051000n,
6751  birthtimeMs: 1318289051000n,
6752  atimeNs: 1318289051000000000n,
6753  mtimeNs: 1318289051000000000n,
6754  ctimeNs: 1318289051000000000n,
6755  birthtimeNs: 1318289051000000000n,
6756  atime: Mon, 10 Oct 2011 23:24:11 GMT,
6757  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
6758  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
6759  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
6760```
6761
6762#### `stats.isBlockDevice()`
6763
6764<!-- YAML
6765added: v0.1.10
6766-->
6767
6768* Returns: {boolean}
6769
6770Returns `true` if the {fs.Stats} object describes a block device.
6771
6772#### `stats.isCharacterDevice()`
6773
6774<!-- YAML
6775added: v0.1.10
6776-->
6777
6778* Returns: {boolean}
6779
6780Returns `true` if the {fs.Stats} object describes a character device.
6781
6782#### `stats.isDirectory()`
6783
6784<!-- YAML
6785added: v0.1.10
6786-->
6787
6788* Returns: {boolean}
6789
6790Returns `true` if the {fs.Stats} object describes a file system directory.
6791
6792If the {fs.Stats} object was obtained from [`fs.lstat()`][], this method will
6793always return `false`. This is because [`fs.lstat()`][] returns information
6794about a symbolic link itself and not the path it resolves to.
6795
6796#### `stats.isFIFO()`
6797
6798<!-- YAML
6799added: v0.1.10
6800-->
6801
6802* Returns: {boolean}
6803
6804Returns `true` if the {fs.Stats} object describes a first-in-first-out (FIFO)
6805pipe.
6806
6807#### `stats.isFile()`
6808
6809<!-- YAML
6810added: v0.1.10
6811-->
6812
6813* Returns: {boolean}
6814
6815Returns `true` if the {fs.Stats} object describes a regular file.
6816
6817#### `stats.isSocket()`
6818
6819<!-- YAML
6820added: v0.1.10
6821-->
6822
6823* Returns: {boolean}
6824
6825Returns `true` if the {fs.Stats} object describes a socket.
6826
6827#### `stats.isSymbolicLink()`
6828
6829<!-- YAML
6830added: v0.1.10
6831-->
6832
6833* Returns: {boolean}
6834
6835Returns `true` if the {fs.Stats} object describes a symbolic link.
6836
6837This method is only valid when using [`fs.lstat()`][].
6838
6839#### `stats.dev`
6840
6841* {number|bigint}
6842
6843The numeric identifier of the device containing the file.
6844
6845#### `stats.ino`
6846
6847* {number|bigint}
6848
6849The file system specific "Inode" number for the file.
6850
6851#### `stats.mode`
6852
6853* {number|bigint}
6854
6855A bit-field describing the file type and mode.
6856
6857#### `stats.nlink`
6858
6859* {number|bigint}
6860
6861The number of hard-links that exist for the file.
6862
6863#### `stats.uid`
6864
6865* {number|bigint}
6866
6867The numeric user identifier of the user that owns the file (POSIX).
6868
6869#### `stats.gid`
6870
6871* {number|bigint}
6872
6873The numeric group identifier of the group that owns the file (POSIX).
6874
6875#### `stats.rdev`
6876
6877* {number|bigint}
6878
6879A numeric device identifier if the file represents a device.
6880
6881#### `stats.size`
6882
6883* {number|bigint}
6884
6885The size of the file in bytes.
6886
6887If the underlying file system does not support getting the size of the file,
6888this will be `0`.
6889
6890#### `stats.blksize`
6891
6892* {number|bigint}
6893
6894The file system block size for i/o operations.
6895
6896#### `stats.blocks`
6897
6898* {number|bigint}
6899
6900The number of blocks allocated for this file.
6901
6902#### `stats.atimeMs`
6903
6904<!-- YAML
6905added: v8.1.0
6906-->
6907
6908* {number|bigint}
6909
6910The timestamp indicating the last time this file was accessed expressed in
6911milliseconds since the POSIX Epoch.
6912
6913#### `stats.mtimeMs`
6914
6915<!-- YAML
6916added: v8.1.0
6917-->
6918
6919* {number|bigint}
6920
6921The timestamp indicating the last time this file was modified expressed in
6922milliseconds since the POSIX Epoch.
6923
6924#### `stats.ctimeMs`
6925
6926<!-- YAML
6927added: v8.1.0
6928-->
6929
6930* {number|bigint}
6931
6932The timestamp indicating the last time the file status was changed expressed
6933in milliseconds since the POSIX Epoch.
6934
6935#### `stats.birthtimeMs`
6936
6937<!-- YAML
6938added: v8.1.0
6939-->
6940
6941* {number|bigint}
6942
6943The timestamp indicating the creation time of this file expressed in
6944milliseconds since the POSIX Epoch.
6945
6946#### `stats.atimeNs`
6947
6948<!-- YAML
6949added: v12.10.0
6950-->
6951
6952* {bigint}
6953
6954Only present when `bigint: true` is passed into the method that generates
6955the object.
6956The timestamp indicating the last time this file was accessed expressed in
6957nanoseconds since the POSIX Epoch.
6958
6959#### `stats.mtimeNs`
6960
6961<!-- YAML
6962added: v12.10.0
6963-->
6964
6965* {bigint}
6966
6967Only present when `bigint: true` is passed into the method that generates
6968the object.
6969The timestamp indicating the last time this file was modified expressed in
6970nanoseconds since the POSIX Epoch.
6971
6972#### `stats.ctimeNs`
6973
6974<!-- YAML
6975added: v12.10.0
6976-->
6977
6978* {bigint}
6979
6980Only present when `bigint: true` is passed into the method that generates
6981the object.
6982The timestamp indicating the last time the file status was changed expressed
6983in nanoseconds since the POSIX Epoch.
6984
6985#### `stats.birthtimeNs`
6986
6987<!-- YAML
6988added: v12.10.0
6989-->
6990
6991* {bigint}
6992
6993Only present when `bigint: true` is passed into the method that generates
6994the object.
6995The timestamp indicating the creation time of this file expressed in
6996nanoseconds since the POSIX Epoch.
6997
6998#### `stats.atime`
6999
7000<!-- YAML
7001added: v0.11.13
7002-->
7003
7004* {Date}
7005
7006The timestamp indicating the last time this file was accessed.
7007
7008#### `stats.mtime`
7009
7010<!-- YAML
7011added: v0.11.13
7012-->
7013
7014* {Date}
7015
7016The timestamp indicating the last time this file was modified.
7017
7018#### `stats.ctime`
7019
7020<!-- YAML
7021added: v0.11.13
7022-->
7023
7024* {Date}
7025
7026The timestamp indicating the last time the file status was changed.
7027
7028#### `stats.birthtime`
7029
7030<!-- YAML
7031added: v0.11.13
7032-->
7033
7034* {Date}
7035
7036The timestamp indicating the creation time of this file.
7037
7038#### Stat time values
7039
7040The `atimeMs`, `mtimeMs`, `ctimeMs`, `birthtimeMs` properties are
7041numeric values that hold the corresponding times in milliseconds. Their
7042precision is platform specific. When `bigint: true` is passed into the
7043method that generates the object, the properties will be [bigints][],
7044otherwise they will be [numbers][MDN-Number].
7045
7046The `atimeNs`, `mtimeNs`, `ctimeNs`, `birthtimeNs` properties are
7047[bigints][] that hold the corresponding times in nanoseconds. They are
7048only present when `bigint: true` is passed into the method that generates
7049the object. Their precision is platform specific.
7050
7051`atime`, `mtime`, `ctime`, and `birthtime` are
7052[`Date`][MDN-Date] object alternate representations of the various times. The
7053`Date` and number values are not connected. Assigning a new number value, or
7054mutating the `Date` value, will not be reflected in the corresponding alternate
7055representation.
7056
7057The times in the stat object have the following semantics:
7058
7059* `atime` "Access Time": Time when file data last accessed. Changed
7060  by the mknod(2), utimes(2), and read(2) system calls.
7061* `mtime` "Modified Time": Time when file data last modified.
7062  Changed by the mknod(2), utimes(2), and write(2) system calls.
7063* `ctime` "Change Time": Time when file status was last changed
7064  (inode data modification). Changed by the chmod(2), chown(2),
7065  link(2), mknod(2), rename(2), unlink(2), utimes(2),
7066  read(2), and write(2) system calls.
7067* `birthtime` "Birth Time": Time of file creation. Set once when the
7068  file is created. On file systems where birthtime is not available,
7069  this field may instead hold either the `ctime` or
7070  `1970-01-01T00:00Z` (ie, Unix epoch timestamp `0`). This value may be greater
7071  than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants,
7072  also set if the `atime` is explicitly set to an earlier value than the current
7073  `birthtime` using the utimes(2) system call.
7074
7075Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As
7076of 0.12, `ctime` is not "creation time", and on Unix systems, it never was.
7077
7078### Class: `fs.StatFs`
7079
7080<!-- YAML
7081added: v18.15.0
7082-->
7083
7084Provides information about a mounted file system.
7085
7086Objects returned from [`fs.statfs()`][] and its synchronous counterpart are of
7087this type. If `bigint` in the `options` passed to those methods is `true`, the
7088numeric values will be `bigint` instead of `number`.
7089
7090```console
7091StatFs {
7092  type: 1397114950,
7093  bsize: 4096,
7094  blocks: 121938943,
7095  bfree: 61058895,
7096  bavail: 61058895,
7097  files: 999,
7098  ffree: 1000000
7099}
7100```
7101
7102`bigint` version:
7103
7104```console
7105StatFs {
7106  type: 1397114950n,
7107  bsize: 4096n,
7108  blocks: 121938943n,
7109  bfree: 61058895n,
7110  bavail: 61058895n,
7111  files: 999n,
7112  ffree: 1000000n
7113}
7114```
7115
7116#### `statfs.bavail`
7117
7118<!-- YAML
7119added: v18.15.0
7120-->
7121
7122* {number|bigint}
7123
7124Free blocks available to unprivileged users.
7125
7126#### `statfs.bfree`
7127
7128<!-- YAML
7129added: v18.15.0
7130-->
7131
7132* {number|bigint}
7133
7134Free blocks in file system.
7135
7136#### `statfs.blocks`
7137
7138<!-- YAML
7139added: v18.15.0
7140-->
7141
7142* {number|bigint}
7143
7144Total data blocks in file system.
7145
7146#### `statfs.bsize`
7147
7148<!-- YAML
7149added: v18.15.0
7150-->
7151
7152* {number|bigint}
7153
7154Optimal transfer block size.
7155
7156#### `statfs.ffree`
7157
7158<!-- YAML
7159added: v18.15.0
7160-->
7161
7162* {number|bigint}
7163
7164Free file nodes in file system.
7165
7166#### `statfs.files`
7167
7168<!-- YAML
7169added: v18.15.0
7170-->
7171
7172* {number|bigint}
7173
7174Total file nodes in file system.
7175
7176#### `statfs.type`
7177
7178<!-- YAML
7179added: v18.15.0
7180-->
7181
7182* {number|bigint}
7183
7184Type of file system.
7185
7186### Class: `fs.WriteStream`
7187
7188<!-- YAML
7189added: v0.1.93
7190-->
7191
7192* Extends {stream.Writable}
7193
7194Instances of {fs.WriteStream} are created and returned using the
7195[`fs.createWriteStream()`][] function.
7196
7197#### Event: `'close'`
7198
7199<!-- YAML
7200added: v0.1.93
7201-->
7202
7203Emitted when the {fs.WriteStream}'s underlying file descriptor has been closed.
7204
7205#### Event: `'open'`
7206
7207<!-- YAML
7208added: v0.1.93
7209-->
7210
7211* `fd` {integer} Integer file descriptor used by the {fs.WriteStream}.
7212
7213Emitted when the {fs.WriteStream}'s file is opened.
7214
7215#### Event: `'ready'`
7216
7217<!-- YAML
7218added: v9.11.0
7219-->
7220
7221Emitted when the {fs.WriteStream} is ready to be used.
7222
7223Fires immediately after `'open'`.
7224
7225#### `writeStream.bytesWritten`
7226
7227<!-- YAML
7228added: v0.4.7
7229-->
7230
7231The number of bytes written so far. Does not include data that is still queued
7232for writing.
7233
7234#### `writeStream.close([callback])`
7235
7236<!-- YAML
7237added: v0.9.4
7238-->
7239
7240* `callback` {Function}
7241  * `err` {Error}
7242
7243Closes `writeStream`. Optionally accepts a
7244callback that will be executed once the `writeStream`
7245is closed.
7246
7247#### `writeStream.path`
7248
7249<!-- YAML
7250added: v0.1.93
7251-->
7252
7253The path to the file the stream is writing to as specified in the first
7254argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then
7255`writeStream.path` will be a string. If `path` is passed as a {Buffer}, then
7256`writeStream.path` will be a {Buffer}.
7257
7258#### `writeStream.pending`
7259
7260<!-- YAML
7261added: v11.2.0
7262-->
7263
7264* {boolean}
7265
7266This property is `true` if the underlying file has not been opened yet,
7267i.e. before the `'ready'` event is emitted.
7268
7269### `fs.constants`
7270
7271* {Object}
7272
7273Returns an object containing commonly used constants for file system
7274operations.
7275
7276#### FS constants
7277
7278The following constants are exported by `fs.constants` and `fsPromises.constants`.
7279
7280Not every constant will be available on every operating system;
7281this is especially important for Windows, where many of the POSIX specific
7282definitions are not available.
7283For portable applications it is recommended to check for their presence
7284before use.
7285
7286To use more than one constant, use the bitwise OR `|` operator.
7287
7288Example:
7289
7290```mjs
7291import { open, constants } from 'node:fs';
7292
7293const {
7294  O_RDWR,
7295  O_CREAT,
7296  O_EXCL,
7297} = constants;
7298
7299open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
7300  // ...
7301});
7302```
7303
7304##### File access constants
7305
7306The following constants are meant for use as the `mode` parameter passed to
7307[`fsPromises.access()`][], [`fs.access()`][], and [`fs.accessSync()`][].
7308
7309<table>
7310  <tr>
7311    <th>Constant</th>
7312    <th>Description</th>
7313  </tr>
7314  <tr>
7315    <td><code>F_OK</code></td>
7316    <td>Flag indicating that the file is visible to the calling process.
7317     This is useful for determining if a file exists, but says nothing
7318     about <code>rwx</code> permissions. Default if no mode is specified.</td>
7319  </tr>
7320  <tr>
7321    <td><code>R_OK</code></td>
7322    <td>Flag indicating that the file can be read by the calling process.</td>
7323  </tr>
7324  <tr>
7325    <td><code>W_OK</code></td>
7326    <td>Flag indicating that the file can be written by the calling
7327    process.</td>
7328  </tr>
7329  <tr>
7330    <td><code>X_OK</code></td>
7331    <td>Flag indicating that the file can be executed by the calling
7332    process. This has no effect on Windows
7333    (will behave like <code>fs.constants.F_OK</code>).</td>
7334  </tr>
7335</table>
7336
7337The definitions are also available on Windows.
7338
7339##### File copy constants
7340
7341The following constants are meant for use with [`fs.copyFile()`][].
7342
7343<table>
7344  <tr>
7345    <th>Constant</th>
7346    <th>Description</th>
7347  </tr>
7348  <tr>
7349    <td><code>COPYFILE_EXCL</code></td>
7350    <td>If present, the copy operation will fail with an error if the
7351    destination path already exists.</td>
7352  </tr>
7353  <tr>
7354    <td><code>COPYFILE_FICLONE</code></td>
7355    <td>If present, the copy operation will attempt to create a
7356    copy-on-write reflink. If the underlying platform does not support
7357    copy-on-write, then a fallback copy mechanism is used.</td>
7358  </tr>
7359  <tr>
7360    <td><code>COPYFILE_FICLONE_FORCE</code></td>
7361    <td>If present, the copy operation will attempt to create a
7362    copy-on-write reflink. If the underlying platform does not support
7363    copy-on-write, then the operation will fail with an error.</td>
7364  </tr>
7365</table>
7366
7367The definitions are also available on Windows.
7368
7369##### File open constants
7370
7371The following constants are meant for use with `fs.open()`.
7372
7373<table>
7374  <tr>
7375    <th>Constant</th>
7376    <th>Description</th>
7377  </tr>
7378  <tr>
7379    <td><code>O_RDONLY</code></td>
7380    <td>Flag indicating to open a file for read-only access.</td>
7381  </tr>
7382  <tr>
7383    <td><code>O_WRONLY</code></td>
7384    <td>Flag indicating to open a file for write-only access.</td>
7385  </tr>
7386  <tr>
7387    <td><code>O_RDWR</code></td>
7388    <td>Flag indicating to open a file for read-write access.</td>
7389  </tr>
7390  <tr>
7391    <td><code>O_CREAT</code></td>
7392    <td>Flag indicating to create the file if it does not already exist.</td>
7393  </tr>
7394  <tr>
7395    <td><code>O_EXCL</code></td>
7396    <td>Flag indicating that opening a file should fail if the
7397    <code>O_CREAT</code> flag is set and the file already exists.</td>
7398  </tr>
7399  <tr>
7400    <td><code>O_NOCTTY</code></td>
7401    <td>Flag indicating that if path identifies a terminal device, opening the
7402    path shall not cause that terminal to become the controlling terminal for
7403    the process (if the process does not already have one).</td>
7404  </tr>
7405  <tr>
7406    <td><code>O_TRUNC</code></td>
7407    <td>Flag indicating that if the file exists and is a regular file, and the
7408    file is opened successfully for write access, its length shall be truncated
7409    to zero.</td>
7410  </tr>
7411  <tr>
7412    <td><code>O_APPEND</code></td>
7413    <td>Flag indicating that data will be appended to the end of the file.</td>
7414  </tr>
7415  <tr>
7416    <td><code>O_DIRECTORY</code></td>
7417    <td>Flag indicating that the open should fail if the path is not a
7418    directory.</td>
7419  </tr>
7420  <tr>
7421  <td><code>O_NOATIME</code></td>
7422    <td>Flag indicating reading accesses to the file system will no longer
7423    result in an update to the <code>atime</code> information associated with
7424    the file. This flag is available on Linux operating systems only.</td>
7425  </tr>
7426  <tr>
7427    <td><code>O_NOFOLLOW</code></td>
7428    <td>Flag indicating that the open should fail if the path is a symbolic
7429    link.</td>
7430  </tr>
7431  <tr>
7432    <td><code>O_SYNC</code></td>
7433    <td>Flag indicating that the file is opened for synchronized I/O with write
7434    operations waiting for file integrity.</td>
7435  </tr>
7436  <tr>
7437    <td><code>O_DSYNC</code></td>
7438    <td>Flag indicating that the file is opened for synchronized I/O with write
7439    operations waiting for data integrity.</td>
7440  </tr>
7441  <tr>
7442    <td><code>O_SYMLINK</code></td>
7443    <td>Flag indicating to open the symbolic link itself rather than the
7444    resource it is pointing to.</td>
7445  </tr>
7446  <tr>
7447    <td><code>O_DIRECT</code></td>
7448    <td>When set, an attempt will be made to minimize caching effects of file
7449    I/O.</td>
7450  </tr>
7451  <tr>
7452    <td><code>O_NONBLOCK</code></td>
7453    <td>Flag indicating to open the file in nonblocking mode when possible.</td>
7454  </tr>
7455  <tr>
7456    <td><code>UV_FS_O_FILEMAP</code></td>
7457    <td>When set, a memory file mapping is used to access the file. This flag
7458    is available on Windows operating systems only. On other operating systems,
7459    this flag is ignored.</td>
7460  </tr>
7461</table>
7462
7463On Windows, only `O_APPEND`, `O_CREAT`, `O_EXCL`, `O_RDONLY`, `O_RDWR`,
7464`O_TRUNC`, `O_WRONLY`, and `UV_FS_O_FILEMAP` are available.
7465
7466##### File type constants
7467
7468The following constants are meant for use with the {fs.Stats} object's
7469`mode` property for determining a file's type.
7470
7471<table>
7472  <tr>
7473    <th>Constant</th>
7474    <th>Description</th>
7475  </tr>
7476  <tr>
7477    <td><code>S_IFMT</code></td>
7478    <td>Bit mask used to extract the file type code.</td>
7479  </tr>
7480  <tr>
7481    <td><code>S_IFREG</code></td>
7482    <td>File type constant for a regular file.</td>
7483  </tr>
7484  <tr>
7485    <td><code>S_IFDIR</code></td>
7486    <td>File type constant for a directory.</td>
7487  </tr>
7488  <tr>
7489    <td><code>S_IFCHR</code></td>
7490    <td>File type constant for a character-oriented device file.</td>
7491  </tr>
7492  <tr>
7493    <td><code>S_IFBLK</code></td>
7494    <td>File type constant for a block-oriented device file.</td>
7495  </tr>
7496  <tr>
7497    <td><code>S_IFIFO</code></td>
7498    <td>File type constant for a FIFO/pipe.</td>
7499  </tr>
7500  <tr>
7501    <td><code>S_IFLNK</code></td>
7502    <td>File type constant for a symbolic link.</td>
7503  </tr>
7504  <tr>
7505    <td><code>S_IFSOCK</code></td>
7506    <td>File type constant for a socket.</td>
7507  </tr>
7508</table>
7509
7510On Windows, only `S_IFCHR`, `S_IFDIR`, `S_IFLNK`, `S_IFMT`, and `S_IFREG`,
7511are available.
7512
7513##### File mode constants
7514
7515The following constants are meant for use with the {fs.Stats} object's
7516`mode` property for determining the access permissions for a file.
7517
7518<table>
7519  <tr>
7520    <th>Constant</th>
7521    <th>Description</th>
7522  </tr>
7523  <tr>
7524    <td><code>S_IRWXU</code></td>
7525    <td>File mode indicating readable, writable, and executable by owner.</td>
7526  </tr>
7527  <tr>
7528    <td><code>S_IRUSR</code></td>
7529    <td>File mode indicating readable by owner.</td>
7530  </tr>
7531  <tr>
7532    <td><code>S_IWUSR</code></td>
7533    <td>File mode indicating writable by owner.</td>
7534  </tr>
7535  <tr>
7536    <td><code>S_IXUSR</code></td>
7537    <td>File mode indicating executable by owner.</td>
7538  </tr>
7539  <tr>
7540    <td><code>S_IRWXG</code></td>
7541    <td>File mode indicating readable, writable, and executable by group.</td>
7542  </tr>
7543  <tr>
7544    <td><code>S_IRGRP</code></td>
7545    <td>File mode indicating readable by group.</td>
7546  </tr>
7547  <tr>
7548    <td><code>S_IWGRP</code></td>
7549    <td>File mode indicating writable by group.</td>
7550  </tr>
7551  <tr>
7552    <td><code>S_IXGRP</code></td>
7553    <td>File mode indicating executable by group.</td>
7554  </tr>
7555  <tr>
7556    <td><code>S_IRWXO</code></td>
7557    <td>File mode indicating readable, writable, and executable by others.</td>
7558  </tr>
7559  <tr>
7560    <td><code>S_IROTH</code></td>
7561    <td>File mode indicating readable by others.</td>
7562  </tr>
7563  <tr>
7564    <td><code>S_IWOTH</code></td>
7565    <td>File mode indicating writable by others.</td>
7566  </tr>
7567  <tr>
7568    <td><code>S_IXOTH</code></td>
7569    <td>File mode indicating executable by others.</td>
7570  </tr>
7571</table>
7572
7573On Windows, only `S_IRUSR` and `S_IWUSR` are available.
7574
7575## Notes
7576
7577### Ordering of callback and promise-based operations
7578
7579Because they are executed asynchronously by the underlying thread pool,
7580there is no guaranteed ordering when using either the callback or
7581promise-based methods.
7582
7583For example, the following is prone to error because the `fs.stat()`
7584operation might complete before the `fs.rename()` operation:
7585
7586```js
7587const fs = require('node:fs');
7588
7589fs.rename('/tmp/hello', '/tmp/world', (err) => {
7590  if (err) throw err;
7591  console.log('renamed complete');
7592});
7593fs.stat('/tmp/world', (err, stats) => {
7594  if (err) throw err;
7595  console.log(`stats: ${JSON.stringify(stats)}`);
7596});
7597```
7598
7599It is important to correctly order the operations by awaiting the results
7600of one before invoking the other:
7601
7602```mjs
7603import { rename, stat } from 'node:fs/promises';
7604
7605const oldPath = '/tmp/hello';
7606const newPath = '/tmp/world';
7607
7608try {
7609  await rename(oldPath, newPath);
7610  const stats = await stat(newPath);
7611  console.log(`stats: ${JSON.stringify(stats)}`);
7612} catch (error) {
7613  console.error('there was an error:', error.message);
7614}
7615```
7616
7617```cjs
7618const { rename, stat } = require('node:fs/promises');
7619
7620(async function(oldPath, newPath) {
7621  try {
7622    await rename(oldPath, newPath);
7623    const stats = await stat(newPath);
7624    console.log(`stats: ${JSON.stringify(stats)}`);
7625  } catch (error) {
7626    console.error('there was an error:', error.message);
7627  }
7628})('/tmp/hello', '/tmp/world');
7629```
7630
7631Or, when using the callback APIs, move the `fs.stat()` call into the callback
7632of the `fs.rename()` operation:
7633
7634```mjs
7635import { rename, stat } from 'node:fs';
7636
7637rename('/tmp/hello', '/tmp/world', (err) => {
7638  if (err) throw err;
7639  stat('/tmp/world', (err, stats) => {
7640    if (err) throw err;
7641    console.log(`stats: ${JSON.stringify(stats)}`);
7642  });
7643});
7644```
7645
7646```cjs
7647const { rename, stat } = require('node:fs/promises');
7648
7649rename('/tmp/hello', '/tmp/world', (err) => {
7650  if (err) throw err;
7651  stat('/tmp/world', (err, stats) => {
7652    if (err) throw err;
7653    console.log(`stats: ${JSON.stringify(stats)}`);
7654  });
7655});
7656```
7657
7658### File paths
7659
7660Most `fs` operations accept file paths that may be specified in the form of
7661a string, a {Buffer}, or a {URL} object using the `file:` protocol.
7662
7663#### String paths
7664
7665String paths are interpreted as UTF-8 character sequences identifying
7666the absolute or relative filename. Relative paths will be resolved relative
7667to the current working directory as determined by calling `process.cwd()`.
7668
7669Example using an absolute path on POSIX:
7670
7671```mjs
7672import { open } from 'node:fs/promises';
7673
7674let fd;
7675try {
7676  fd = await open('/open/some/file.txt', 'r');
7677  // Do something with the file
7678} finally {
7679  await fd?.close();
7680}
7681```
7682
7683Example using a relative path on POSIX (relative to `process.cwd()`):
7684
7685```mjs
7686import { open } from 'node:fs/promises';
7687
7688let fd;
7689try {
7690  fd = await open('file.txt', 'r');
7691  // Do something with the file
7692} finally {
7693  await fd?.close();
7694}
7695```
7696
7697#### File URL paths
7698
7699<!-- YAML
7700added: v7.6.0
7701-->
7702
7703For most `node:fs` module functions, the `path` or `filename` argument may be
7704passed as a {URL} object using the `file:` protocol.
7705
7706```mjs
7707import { readFileSync } from 'node:fs';
7708
7709readFileSync(new URL('file:///tmp/hello'));
7710```
7711
7712`file:` URLs are always absolute paths.
7713
7714##### Platform-specific considerations
7715
7716On Windows, `file:` {URL}s with a host name convert to UNC paths, while `file:`
7717{URL}s with drive letters convert to local absolute paths. `file:` {URL}s
7718with no host name and no drive letter will result in an error:
7719
7720```mjs
7721import { readFileSync } from 'node:fs';
7722// On Windows :
7723
7724// - WHATWG file URLs with hostname convert to UNC path
7725// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
7726readFileSync(new URL('file://hostname/p/a/t/h/file'));
7727
7728// - WHATWG file URLs with drive letters convert to absolute path
7729// file:///C:/tmp/hello => C:\tmp\hello
7730readFileSync(new URL('file:///C:/tmp/hello'));
7731
7732// - WHATWG file URLs without hostname must have a drive letters
7733readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
7734readFileSync(new URL('file:///c/p/a/t/h/file'));
7735// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
7736```
7737
7738`file:` {URL}s with drive letters must use `:` as a separator just after
7739the drive letter. Using another separator will result in an error.
7740
7741On all other platforms, `file:` {URL}s with a host name are unsupported and
7742will result in an error:
7743
7744```mjs
7745import { readFileSync } from 'node:fs';
7746// On other platforms:
7747
7748// - WHATWG file URLs with hostname are unsupported
7749// file://hostname/p/a/t/h/file => throw!
7750readFileSync(new URL('file://hostname/p/a/t/h/file'));
7751// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
7752
7753// - WHATWG file URLs convert to absolute path
7754// file:///tmp/hello => /tmp/hello
7755readFileSync(new URL('file:///tmp/hello'));
7756```
7757
7758A `file:` {URL} having encoded slash characters will result in an error on all
7759platforms:
7760
7761```mjs
7762import { readFileSync } from 'node:fs';
7763
7764// On Windows
7765readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
7766readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
7767/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
7768\ or / characters */
7769
7770// On POSIX
7771readFileSync(new URL('file:///p/a/t/h/%2F'));
7772readFileSync(new URL('file:///p/a/t/h/%2f'));
7773/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
7774/ characters */
7775```
7776
7777On Windows, `file:` {URL}s having encoded backslash will result in an error:
7778
7779```mjs
7780import { readFileSync } from 'node:fs';
7781
7782// On Windows
7783readFileSync(new URL('file:///C:/path/%5C'));
7784readFileSync(new URL('file:///C:/path/%5c'));
7785/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
7786\ or / characters */
7787```
7788
7789#### Buffer paths
7790
7791Paths specified using a {Buffer} are useful primarily on certain POSIX
7792operating systems that treat file paths as opaque byte sequences. On such
7793systems, it is possible for a single file path to contain sub-sequences that
7794use multiple character encodings. As with string paths, {Buffer} paths may
7795be relative or absolute:
7796
7797Example using an absolute path on POSIX:
7798
7799```mjs
7800import { open } from 'node:fs/promises';
7801import { Buffer } from 'node:buffer';
7802
7803let fd;
7804try {
7805  fd = await open(Buffer.from('/open/some/file.txt'), 'r');
7806  // Do something with the file
7807} finally {
7808  await fd?.close();
7809}
7810```
7811
7812#### Per-drive working directories on Windows
7813
7814On Windows, Node.js follows the concept of per-drive working directory. This
7815behavior can be observed when using a drive path without a backslash. For
7816example `fs.readdirSync('C:\\')` can potentially return a different result than
7817`fs.readdirSync('C:')`. For more information, see
7818[this MSDN page][MSDN-Rel-Path].
7819
7820### File descriptors
7821
7822On POSIX systems, for every process, the kernel maintains a table of currently
7823open files and resources. Each open file is assigned a simple numeric
7824identifier called a _file descriptor_. At the system-level, all file system
7825operations use these file descriptors to identify and track each specific
7826file. Windows systems use a different but conceptually similar mechanism for
7827tracking resources. To simplify things for users, Node.js abstracts away the
7828differences between operating systems and assigns all open files a numeric file
7829descriptor.
7830
7831The callback-based `fs.open()`, and synchronous `fs.openSync()` methods open a
7832file and allocate a new file descriptor. Once allocated, the file descriptor may
7833be used to read data from, write data to, or request information about the file.
7834
7835Operating systems limit the number of file descriptors that may be open
7836at any given time so it is critical to close the descriptor when operations
7837are completed. Failure to do so will result in a memory leak that will
7838eventually cause an application to crash.
7839
7840```mjs
7841import { open, close, fstat } from 'node:fs';
7842
7843function closeFd(fd) {
7844  close(fd, (err) => {
7845    if (err) throw err;
7846  });
7847}
7848
7849open('/open/some/file.txt', 'r', (err, fd) => {
7850  if (err) throw err;
7851  try {
7852    fstat(fd, (err, stat) => {
7853      if (err) {
7854        closeFd(fd);
7855        throw err;
7856      }
7857
7858      // use stat
7859
7860      closeFd(fd);
7861    });
7862  } catch (err) {
7863    closeFd(fd);
7864    throw err;
7865  }
7866});
7867```
7868
7869The promise-based APIs use a {FileHandle} object in place of the numeric
7870file descriptor. These objects are better managed by the system to ensure
7871that resources are not leaked. However, it is still required that they are
7872closed when operations are completed:
7873
7874```mjs
7875import { open } from 'node:fs/promises';
7876
7877let file;
7878try {
7879  file = await open('/open/some/file.txt', 'r');
7880  const stat = await file.stat();
7881  // use stat
7882} finally {
7883  await file.close();
7884}
7885```
7886
7887### Threadpool usage
7888
7889All callback and promise-based file system APIs (with the exception of
7890`fs.FSWatcher()`) use libuv's threadpool. This can have surprising and negative
7891performance implications for some applications. See the
7892[`UV_THREADPOOL_SIZE`][] documentation for more information.
7893
7894### File system flags
7895
7896The following flags are available wherever the `flag` option takes a
7897string.
7898
7899* `'a'`: Open file for appending.
7900  The file is created if it does not exist.
7901
7902* `'ax'`: Like `'a'` but fails if the path exists.
7903
7904* `'a+'`: Open file for reading and appending.
7905  The file is created if it does not exist.
7906
7907* `'ax+'`: Like `'a+'` but fails if the path exists.
7908
7909* `'as'`: Open file for appending in synchronous mode.
7910  The file is created if it does not exist.
7911
7912* `'as+'`: Open file for reading and appending in synchronous mode.
7913  The file is created if it does not exist.
7914
7915* `'r'`: Open file for reading.
7916  An exception occurs if the file does not exist.
7917
7918* `'rs'`: Open file for reading in synchronous mode.
7919  An exception occurs if the file does not exist.
7920
7921* `'r+'`: Open file for reading and writing.
7922  An exception occurs if the file does not exist.
7923
7924* `'rs+'`: Open file for reading and writing in synchronous mode. Instructs
7925  the operating system to bypass the local file system cache.
7926
7927  This is primarily useful for opening files on NFS mounts as it allows
7928  skipping the potentially stale local cache. It has a very real impact on
7929  I/O performance so using this flag is not recommended unless it is needed.
7930
7931  This doesn't turn `fs.open()` or `fsPromises.open()` into a synchronous
7932  blocking call. If synchronous operation is desired, something like
7933  `fs.openSync()` should be used.
7934
7935* `'w'`: Open file for writing.
7936  The file is created (if it does not exist) or truncated (if it exists).
7937
7938* `'wx'`: Like `'w'` but fails if the path exists.
7939
7940* `'w+'`: Open file for reading and writing.
7941  The file is created (if it does not exist) or truncated (if it exists).
7942
7943* `'wx+'`: Like `'w+'` but fails if the path exists.
7944
7945`flag` can also be a number as documented by open(2); commonly used constants
7946are available from `fs.constants`. On Windows, flags are translated to
7947their equivalent ones where applicable, e.g. `O_WRONLY` to `FILE_GENERIC_WRITE`,
7948or `O_EXCL|O_CREAT` to `CREATE_NEW`, as accepted by `CreateFileW`.
7949
7950The exclusive flag `'x'` (`O_EXCL` flag in open(2)) causes the operation to
7951return an error if the path already exists. On POSIX, if the path is a symbolic
7952link, using `O_EXCL` returns an error even if the link is to a path that does
7953not exist. The exclusive flag might not work with network file systems.
7954
7955On Linux, positional writes don't work when the file is opened in append mode.
7956The kernel ignores the position argument and always appends the data to
7957the end of the file.
7958
7959Modifying a file rather than replacing it may require the `flag` option to be
7960set to `'r+'` rather than the default `'w'`.
7961
7962The behavior of some flags are platform-specific. As such, opening a directory
7963on macOS and Linux with the `'a+'` flag, as in the example below, will return an
7964error. In contrast, on Windows and FreeBSD, a file descriptor or a `FileHandle`
7965will be returned.
7966
7967```js
7968// macOS and Linux
7969fs.open('<directory>', 'a+', (err, fd) => {
7970  // => [Error: EISDIR: illegal operation on a directory, open <directory>]
7971});
7972
7973// Windows and FreeBSD
7974fs.open('<directory>', 'a+', (err, fd) => {
7975  // => null, <fd>
7976});
7977```
7978
7979On Windows, opening an existing hidden file using the `'w'` flag (either
7980through `fs.open()`, `fs.writeFile()`, or `fsPromises.open()`) will fail with
7981`EPERM`. Existing hidden files can be opened for writing with the `'r+'` flag.
7982
7983A call to `fs.ftruncate()` or `filehandle.truncate()` can be used to reset
7984the file contents.
7985
7986[#25741]: https://github.com/nodejs/node/issues/25741
7987[Common System Errors]: errors.md#common-system-errors
7988[FS constants]: #fs-constants
7989[File access constants]: #file-access-constants
7990[MDN-Date]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
7991[MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
7992[MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
7993[MSDN-Using-Streams]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams
7994[Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file
7995[`AHAFS`]: https://developer.ibm.com/articles/au-aix_event_infrastructure/
7996[`Buffer.byteLength`]: buffer.md#static-method-bufferbytelengthstring-encoding
7997[`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
7998[`Number.MAX_SAFE_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
7999[`ReadDirectoryChangesW`]: https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw
8000[`UV_THREADPOOL_SIZE`]: cli.md#uv_threadpool_sizesize
8001[`dirent.parentPath`]: #direntparentpath
8002[`event ports`]: https://illumos.org/man/port_create
8003[`filehandle.createReadStream()`]: #filehandlecreatereadstreamoptions
8004[`filehandle.createWriteStream()`]: #filehandlecreatewritestreamoptions
8005[`filehandle.writeFile()`]: #filehandlewritefiledata-options
8006[`fs.access()`]: #fsaccesspath-mode-callback
8007[`fs.accessSync()`]: #fsaccesssyncpath-mode
8008[`fs.chmod()`]: #fschmodpath-mode-callback
8009[`fs.chown()`]: #fschownpath-uid-gid-callback
8010[`fs.copyFile()`]: #fscopyfilesrc-dest-mode-callback
8011[`fs.copyFileSync()`]: #fscopyfilesyncsrc-dest-mode
8012[`fs.createReadStream()`]: #fscreatereadstreampath-options
8013[`fs.createWriteStream()`]: #fscreatewritestreampath-options
8014[`fs.exists()`]: #fsexistspath-callback
8015[`fs.fstat()`]: #fsfstatfd-options-callback
8016[`fs.ftruncate()`]: #fsftruncatefd-len-callback
8017[`fs.futimes()`]: #fsfutimesfd-atime-mtime-callback
8018[`fs.lstat()`]: #fslstatpath-options-callback
8019[`fs.lutimes()`]: #fslutimespath-atime-mtime-callback
8020[`fs.mkdir()`]: #fsmkdirpath-options-callback
8021[`fs.mkdtemp()`]: #fsmkdtempprefix-options-callback
8022[`fs.open()`]: #fsopenpath-flags-mode-callback
8023[`fs.opendir()`]: #fsopendirpath-options-callback
8024[`fs.opendirSync()`]: #fsopendirsyncpath-options
8025[`fs.read()`]: #fsreadfd-buffer-offset-length-position-callback
8026[`fs.readFile()`]: #fsreadfilepath-options-callback
8027[`fs.readFileSync()`]: #fsreadfilesyncpath-options
8028[`fs.readdir()`]: #fsreaddirpath-options-callback
8029[`fs.readdirSync()`]: #fsreaddirsyncpath-options
8030[`fs.readv()`]: #fsreadvfd-buffers-position-callback
8031[`fs.realpath()`]: #fsrealpathpath-options-callback
8032[`fs.rm()`]: #fsrmpath-options-callback
8033[`fs.rmSync()`]: #fsrmsyncpath-options
8034[`fs.rmdir()`]: #fsrmdirpath-options-callback
8035[`fs.stat()`]: #fsstatpath-options-callback
8036[`fs.statfs()`]: #fsstatfspath-options-callback
8037[`fs.symlink()`]: #fssymlinktarget-path-type-callback
8038[`fs.utimes()`]: #fsutimespath-atime-mtime-callback
8039[`fs.watch()`]: #fswatchfilename-options-listener
8040[`fs.write(fd, buffer...)`]: #fswritefd-buffer-offset-length-position-callback
8041[`fs.write(fd, string...)`]: #fswritefd-string-position-encoding-callback
8042[`fs.writeFile()`]: #fswritefilefile-data-options-callback
8043[`fs.writev()`]: #fswritevfd-buffers-position-callback
8044[`fsPromises.access()`]: #fspromisesaccesspath-mode
8045[`fsPromises.copyFile()`]: #fspromisescopyfilesrc-dest-mode
8046[`fsPromises.open()`]: #fspromisesopenpath-flags-mode
8047[`fsPromises.opendir()`]: #fspromisesopendirpath-options
8048[`fsPromises.rm()`]: #fspromisesrmpath-options
8049[`fsPromises.stat()`]: #fspromisesstatpath-options
8050[`fsPromises.utimes()`]: #fspromisesutimespath-atime-mtime
8051[`inotify(7)`]: https://man7.org/linux/man-pages/man7/inotify.7.html
8052[`kqueue(2)`]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
8053[`util.promisify()`]: util.md#utilpromisifyoriginal
8054[bigints]: https://tc39.github.io/proposal-bigint
8055[caveats]: #caveats
8056[chcp]: https://ss64.com/nt/chcp.html
8057[inode]: https://en.wikipedia.org/wiki/Inode
8058[support of file system `flags`]: #file-system-flags
8059