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