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