Skip to main content
node__fs.d.ts - Node documentation

Usage in Deno

```typescript import * as mod from "node:node__fs.d.ts"; ```
The `node:fs` module enables interacting with the file system in a way modeled on standard POSIX functions. To use the promise-based APIs: ```js import * as fs from 'node:fs/promises'; ``` To use the callback and sync APIs: ```js import * as fs from 'node:fs'; ``` All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).

Classes

c
Dir
A class representing a directory stream. Created by [opendir](.././node__fs.d.ts/~/opendir), [opendirSync](.././node__fs.d.ts/~/opendirSync), or `fsPromises.opendir()`. ```js import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); for await (const dirent of dir) console.log(dirent.name); } catch (err) { console.error(err); } ``` When using the async iterator, the `fs.Dir` object will be automatically closed after the iterator exits.
c
Dirent
A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an `fs.Dir`. The directory entry is a combination of the file name and file type pairs. Additionally, when [readdir](.././node__fs.d.ts/~/readdir) or [readdirSync](.././node__fs.d.ts/~/readdirSync) is called with the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s.
c
ReadStream
Instances of `fs.ReadStream` are created and returned using the [createReadStream](.././node__fs.d.ts/~/createReadStream) function.
c
WriteStream
* Extends `stream.Writable` Instances of `fs.WriteStream` are created and returned using the [createWriteStream](.././node__fs.d.ts/~/createWriteStream) function.

Functions

f
access
Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for possible values of `mode`. The final argument, `callback`, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. ```js import { access, constants } from 'node:fs'; const file = 'package.json'; // Check if the file exists in the current directory. access(file, constants.F_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); }); // Check if the file is readable. access(file, constants.R_OK, (err) => { console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); }); // Check if the file is writable. access(file, constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); }); // Check if the file is readable and writable. access(file, constants.R_OK | constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); }); ``` Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. **write (NOT RECOMMENDED)** ```js import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (!err) { console.error('myfile already exists'); return; } open('myfile', 'wx', (err, fd) => { if (err) throw err; try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); }); ``` **write (RECOMMENDED)** ```js import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` **read (NOT RECOMMENDED)** ```js import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } open('myfile', 'r', (err, fd) => { if (err) throw err; try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); }); ``` **read (RECOMMENDED)** ```js import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any. In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process. On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The `fs.access()` function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.
f
accessSync
Synchronously tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for possible values of `mode`. If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, the method will return `undefined`. ```js import { accessSync, constants } from 'node:fs'; try { accessSync('etc/passwd', constants.R_OK | constants.W_OK); console.log('can read/write'); } catch (err) { console.error('no access!'); } ```
f
appendFile
Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a `Buffer`. The `mode` option only affects the newly created file. See [open](.././node__fs.d.ts/~/open) for more details. ```js import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); }); ``` If `options` is a string, then it specifies the encoding: ```js import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback); ``` The `path` may be specified as a numeric file descriptor that has been opened for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. ```js import { open, close, appendFile } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('message.txt', 'a', (err, fd) => { if (err) throw err; try { appendFile(fd, 'data to append', 'utf8', (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); throw err; } }); ```
f
appendFileSync
Synchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a `Buffer`. The `mode` option only affects the newly created file. See [open](.././node__fs.d.ts/~/open) for more details. ```js import { appendFileSync } from 'node:fs'; try { appendFileSync('message.txt', 'data to append'); console.log('The "data to append" was appended to file!'); } catch (err) { // Handle the error } ``` If `options` is a string, then it specifies the encoding: ```js import { appendFileSync } from 'node:fs'; appendFileSync('message.txt', 'data to append', 'utf8'); ``` The `path` may be specified as a numeric file descriptor that has been opened for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. ```js import { openSync, closeSync, appendFileSync } from 'node:fs'; let fd; try { fd = openSync('message.txt', 'a'); appendFileSync(fd, 'data to append', 'utf8'); } catch (err) { // Handle the error } finally { if (fd !== undefined) closeSync(fd); } ```
f
chmod
Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback. See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. ```js import { chmod } from 'node:fs'; chmod('my_file.txt', 0o775, (err) => { if (err) throw err; console.log('The permissions for file "my_file.txt" have been changed!'); }); ```
f
chmodSync
For detailed information, see the documentation of the asynchronous version of this API: [chmod](.././node__fs.d.ts/~/chmod). See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
f
chown
Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback. See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
f
chownSync
Synchronously changes owner and group of a file. Returns `undefined`. This is the synchronous version of [chown](.././node__fs.d.ts/~/chown). See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
f
close
Closes the file descriptor. No arguments other than a possible exception are given to the completion callback. Calling `fs.close()` on any file descriptor (`fd`) that is currently in use through any other `fs` operation may lead to undefined behavior. See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
f
closeSync
Closes the file descriptor. Returns `undefined`. Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use through any other `fs` operation may lead to undefined behavior. See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
f
copyFile
Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination. `mode` is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already exists. * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used. * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail. ```js import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); ```
f
copyFileSync
Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. Returns `undefined`. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination. `mode` is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already exists. * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used. * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail. ```js import { copyFileSync, constants } from 'node:fs'; // destination.txt will be created or overwritten by default. copyFileSync('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); ```
f
cp
Asynchronously copies the entire directory structure from `src` to `dest`, including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`.
f
cpSync
Synchronously copies the entire directory structure from `src` to `dest`, including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`.
f
createReadStream
Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream returned by this method has a default `highWaterMark` of 64 KiB. `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start counting at 0, allowed values are in the \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is omitted or `undefined`, `fs.createReadStream()` reads sequentially from the current file position. The `encoding` can be any one of those accepted by `Buffer`. If `fd` is specified, `ReadStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. If `fd` points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. ```js import { createReadStream } from 'node:fs'; // Create a stream from some character device. const stream = createReadStream('/dev/input/event0'); setTimeout(() => { stream.close(); // This may not close the stream. // Artificially marking end-of-stream, as if the underlying resource had // indicated end-of-file by itself, allows the stream to close. // This does not cancel pending read operations, and if there is such an // operation, the process may still not be able to exit successfully // until it finishes. stream.push(null); stream.read(0); }, 100); ``` If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If `autoClose` is set to true (default behavior), on `'error'` or `'end'` the file descriptor will be closed automatically. `mode` sets the file mode (permission and sticky bits), but only if the file was created. An example to read the last 10 bytes of a file which is 100 bytes long: ```js import { createReadStream } from 'node:fs'; createReadStream('sample.txt', { start: 90, end: 99 }); ``` If `options` is a string, then it specifies the encoding.
f
createWriteStream
`options` may also include a `start` option to allow writing data at some position past the beginning of the file, allowed values are in the \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than replacing it may require the `flags` option to be set to `r+` rather than the default `w`. The `encoding` can be any one of those accepted by `Buffer`. If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce performance as some optimizations (`_writev()`) will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. If `options` is a string, then it specifies the encoding.
f
existsSync
Returns `true` if the path exists, `false` otherwise. For detailed information, see the documentation of the asynchronous version of this API: [exists](.././node__fs.d.ts/~/exists). `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other Node.js callbacks. `fs.existsSync()` does not use a callback. ```js import { existsSync } from 'node:fs'; if (existsSync('/etc/passwd')) console.log('The path exists.'); ```
f
fchmod
Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback. See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
f
fchmodSync
Sets the permissions on the file. Returns `undefined`. See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
f
fchown
Sets the owner of the file. No arguments other than a possible exception are given to the completion callback. See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
f
fchownSync
Sets the owner of the file. Returns `undefined`. See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
f
fdatasync
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other than a possible exception are given to the completion callback.
f
fdatasyncSync
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`.
f
fstat
Invokes the callback with the `fs.Stats` for the file descriptor. See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
f
fstatSync
Retrieves the `fs.Stats` for the file descriptor. See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
f
fsync
Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other than a possible exception are given to the completion callback.
f
fsyncSync
Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`.
f
ftruncate
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback. See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file. For example, the following program retains only the first four bytes of the file: ```js import { open, close, ftruncate } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('temp.txt', 'r+', (err, fd) => { if (err) throw err; try { ftruncate(fd, 4, (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); if (err) throw err; } }); ``` If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used.
f
ftruncateSync
Truncates the file descriptor. Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [ftruncate](.././node__fs.d.ts/~/ftruncate).
f
futimes
Change the file system timestamps of the object referenced by the supplied file descriptor. See [utimes](.././node__fs.d.ts/~/utimes).
f
futimesSync
Synchronous version of [futimes](.././node__fs.d.ts/~/futimes). Returns `undefined`.
f
glob
Retrieves the files matching the specified pattern.
f
globSync
Retrieves the files matching the specified pattern.
f
lchown
Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback. See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail.
f
lchownSync
Set the owner for the path. Returns `undefined`. See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details.
f
linkSync
Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`.
f
lstat
Retrieves the `fs.Stats` for the symbolic link referred to by the path. The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details.
f
lutimes
Changes the access and modification times of a file in the same way as [utimes](.././node__fs.d.ts/~/utimes), with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed. No arguments other than a possible exception are given to the completion callback.
f
lutimesSync
Change the file system timestamps of the symbolic link referenced by `path`. Returns `undefined`, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of [lutimes](.././node__fs.d.ts/~/lutimes).
f
mkdir
Asynchronously creates a directory. The callback is given a possible exception and, if `recursive` is `true`, the first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was created (for instance, if it was previously created). The optional `options` argument can be an integer specifying `mode` (permission and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that exists results in an error only when `recursive` is false. If `recursive` is false and the directory exists, an `EEXIST` error occurs. ```js import { mkdir } from 'node:fs'; // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. mkdir('./tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; }); ``` On Windows, using `fs.mkdir()` on the root directory even with recursion will result in an error: ```js import { mkdir } from 'node:fs'; mkdir('/', { recursive: true }, (err) => { // => [Error: EPERM: operation not permitted, mkdir 'C:\'] }); ``` See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
f
mkdirSync
Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. This is the synchronous version of [mkdir](.././node__fs.d.ts/~/mkdir). See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
f
mkdtemp
Creates a unique temporary directory. Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing `X` characters in `prefix` with random characters. The created directory path is passed as a string to the callback's second parameter. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ```js import { mkdtemp } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { if (err) throw err; console.log(directory); // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 }); ``` The `fs.mkdtemp()` method will append the six randomly selected characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator (`import { sep } from 'node:path'`). ```js import { tmpdir } from 'node:os'; import { mkdtemp } from 'node:fs'; // The parent directory for the new temporary directory const tmpDir = tmpdir(); // This method is *INCORRECT*: mkdtemp(tmpDir, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmpabc123`. // A new temporary directory is created at the file system root // rather than *within* the /tmp directory. }); // This method is *CORRECT*: import { sep } from 'node:path'; mkdtemp(`${tmpDir}${sep}`, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmp/abc123`. // A new temporary directory is created within // the /tmp directory. }); ```
f
mkdtempSync
Returns the created directory path. For detailed information, see the documentation of the asynchronous version of this API: [mkdtemp](.././node__fs.d.ts/~/mkdtemp). The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use.
f
open
Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. `mode` sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see [chmod](.././node__fs.d.ts/~/chmod). The callback gets two arguments `(err, fd)`. Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc.
f
openAsBlob
Returns a `Blob` whose data is backed by the given file. The file must not be modified after the `Blob` is created. Any modifications will cause reading the `Blob` data to fail with a `DOMException` error. Synchronous stat operations on the file when the `Blob` is created, and before each read in order to detect whether the file data has been modified on disk. ```js import { openAsBlob } from 'node:fs'; const blob = await openAsBlob('the.file.txt'); const ab = await blob.arrayBuffer(); blob.stream(); ```
f
opendir
Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more details. Creates an `fs.Dir`, which contains all further functions for reading from and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations.
f
opendirSync
Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). Creates an `fs.Dir`, which contains all further functions for reading from and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations.
f
openSync
Returns an integer representing the file descriptor. For detailed information, see the documentation of the asynchronous version of this API: [open](.././node__fs.d.ts/~/open).
f
promises.access
Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for possible values of `mode`. If the accessibility check is successful, the promise is fulfilled with no value. If any of the accessibility checks fail, the promise is rejected with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and written by the current process. ```js import { access, constants } from 'node:fs/promises'; try { await access('/etc/passwd', constants.R_OK | constants.W_OK); console.log('can access'); } catch { console.error('cannot access'); } ``` Using `fsPromises.access()` to check for the accessibility of a file before calling `fsPromises.open()` is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.
f
promises.appendFile
Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a `Buffer`. If `options` is a string, then it specifies the `encoding`. The `mode` option only affects the newly created file. See `fs.open()` for more details. The `path` may be specified as a `FileHandle` that has been opened for appending (using `fsPromises.open()`).
f
promises.chmod
Changes the permissions of a file.
f
promises.chown
Changes the ownership of a file.
f
promises.copyFile
Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. No guarantees are made about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination. ```js import { copyFile, constants } from 'node:fs/promises'; try { await copyFile('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); } catch { console.error('The file could not be copied'); } // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. try { await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); console.log('source.txt was copied to destination.txt'); } catch { console.error('The file could not be copied'); } ```
f
promises.cp
Asynchronously copies the entire directory structure from `src` to `dest`, including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`.
f
promises.glob
Retrieves the files matching the specified pattern.
f
promises.lchown
Changes the ownership on a symbolic link.
f
promises.lstat
Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail.
f
promises.lutimes
Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.
f
promises.mkdir
Asynchronously creates a directory. The optional `options` argument can be an integer specifying `mode` (permission and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory that exists results in a rejection only when `recursive` is false. ```js import { mkdir } from 'node:fs/promises'; try { const projectFolder = new URL('./test/project/', import.meta.url); const createDir = await mkdir(projectFolder, { recursive: true }); console.log(`created ${createDir}`); } catch (err) { console.error(err.message); } ```
f
promises.mkdtemp
Creates a unique temporary directory. A unique directory name is generated by appending six random characters to the end of the provided `prefix`. Due to platform inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing `X` characters in `prefix` with random characters. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ```js import { mkdtemp } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; try { await mkdtemp(join(tmpdir(), 'foo-')); } catch (err) { console.error(err); } ``` The `fsPromises.mkdtemp()` method will append the six randomly selected characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing platform-specific path separator (`import { sep } from 'node:path'`).
f
promises.open
Opens a `FileHandle`. Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
f
promises.opendir
Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. Creates an `fs.Dir`, which contains all further functions for reading from and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations. Example using async iteration: ```js import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); for await (const dirent of dir) console.log(dirent.name); } catch (err) { console.error(err); } ``` When using the async iterator, the `fs.Dir` object will be automatically closed after the iterator exits.
f
promises.readdir
Reads the contents of a directory. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the filenames. If the `encoding` is set to `'buffer'`, the filenames returned will be passed as `Buffer` objects. If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. ```js import { readdir } from 'node:fs/promises'; try { const files = await readdir(path); for (const file of files) console.log(file); } catch (err) { console.error(err); } ```
f
promises.readFile
Asynchronously reads the entire contents of a file. If no encoding is specified (using `options.encoding`), the data is returned as a `Buffer` object. Otherwise, the data will be a string. If `options` is a string, then it specifies the encoding. When the `path` is a directory, the behavior of `fsPromises.readFile()` is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned. An example of reading a `package.json` file located in the same directory of the running code: ```js import { readFile } from 'node:fs/promises'; try { const filePath = new URL('./package.json', import.meta.url); const contents = await readFile(filePath, { encoding: 'utf8' }); console.log(contents); } catch (err) { console.error(err.message); } ``` It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a request is aborted the promise returned is rejected with an `AbortError`: ```js import { readFile } from 'node:fs/promises'; try { const controller = new AbortController(); const { signal } = controller; const promise = readFile(fileName, { signal }); // Abort the request before the promise settles. controller.abort(); await promise; } catch (err) { // When a request is aborted - err is an AbortError console.error(err); } ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.readFile` performs. Any specified `FileHandle` has to support reading.
f
promises.realpath
Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path. If the `encoding` is set to `'buffer'`, the path returned will be passed as a `Buffer` object. On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction.
f
promises.rename
Renames `oldPath` to `newPath`.
f
promises.rm
Removes files and directories (modeled on the standard POSIX `rm` utility).
f
promises.rmdir
Removes the directory identified by `path`. Using `fsPromises.rmdir()` on a file (not a directory) results in the promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`.
f
promises.stat
No documentation available
f
promises.statfs
No documentation available
f
promises.truncate
Truncates (shortens or extends the length) of the content at `path` to `len` bytes.
f
promises.utimes
Change the file system timestamps of the object referenced by `path`. The `atime` and `mtime` arguments follow these rules: * Values can be either numbers representing Unix epoch time, `Date`s, or a numeric string like `'123456789.0'`. * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.
f
promises.watch
Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. ```js import { watch } from 'node:fs/promises'; const ac = new AbortController(); const { signal } = ac; setTimeout(() => ac.abort(), 10000); (async () => { try { const watcher = watch(__filename, { signal }); for await (const event of watcher) console.log(event); } catch (err) { if (err.name === 'AbortError') return; throw err; } })(); ``` On most platforms, `'rename'` is emitted whenever a filename appears or disappears in the directory. All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`.
f
promises.writeFile
Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. The `encoding` option is ignored if `data` is a buffer. If `options` is a string, then it specifies the encoding. The `mode` option only affects the newly created file. See `fs.open()` for more details. Any specified `FileHandle` has to support writing. It is unsafe to use `fsPromises.writeFile()` multiple times on the same file without waiting for the promise to be settled. Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience method that performs multiple `write` calls internally to write the buffer passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. Cancelation is "best effort", and some amount of data is likely still to be written. ```js import { writeFile } from 'node:fs/promises'; import { Buffer } from 'node:buffer'; try { const controller = new AbortController(); const { signal } = controller; const data = new Uint8Array(Buffer.from('Hello Node.js')); const promise = writeFile('message.txt', data, { signal }); // Abort the request before the promise settles. controller.abort(); await promise; } catch (err) { // When a request is aborted - err is an AbortError console.error(err); } ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs.
f
read
Read data from the file specified by `fd`. The callback is given the three arguments, `(err, bytesRead, buffer)`. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. If this method is invoked as its `util.promisify()` ed version, it returns a promise for an `Object` with `bytesRead` and `buffer` properties.
f
readdir
Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the filenames passed to the callback. If the `encoding` is set to `'buffer'`, the filenames returned will be passed as `Buffer` objects. If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects.
f
readdirSync
Reads the contents of the directory. See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the filenames returned. If the `encoding` is set to `'buffer'`, the filenames returned will be passed as `Buffer` objects. If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects.
f
readFile
Asynchronously reads the entire contents of a file. ```js import { readFile } from 'node:fs'; readFile('/etc/passwd', (err, data) => { if (err) throw err; console.log(data); }); ``` The callback is passed two arguments `(err, data)`, where `data` is the contents of the file. If no encoding is specified, then the raw buffer is returned. If `options` is a string, then it specifies the encoding: ```js import { readFile } from 'node:fs'; readFile('/etc/passwd', 'utf8', callback); ``` When the path is a directory, the behavior of `fs.readFile()` and [readFileSync](.././node__fs.d.ts/~/readFileSync) is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned. ```js import { readFile } from 'node:fs'; // macOS, Linux, and Windows readFile('', (err, data) => { // => [Error: EISDIR: illegal operation on a directory, read ] }); // FreeBSD readFile('', (err, data) => { // => null, }); ``` It is possible to abort an ongoing request using an `AbortSignal`. If a request is aborted the callback is called with an `AbortError`: ```js import { readFile } from 'node:fs'; const controller = new AbortController(); const signal = controller.signal; readFile(fileInfo[0].name, { signal }, (err, buf) => { // ... }); // When you want to abort the request controller.abort(); ``` The `fs.readFile()` function buffers the entire file. To minimize memory costs, when possible prefer streaming via `fs.createReadStream()`. Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.readFile` performs.
f
readFileSync
Returns the contents of the `path`. For detailed information, see the documentation of the asynchronous version of this API: [readFile](.././node__fs.d.ts/~/readFile). If the `encoding` option is specified then this function returns a string. Otherwise it returns a buffer. Similar to [readFile](.././node__fs.d.ts/~/readFile), when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. ```js import { readFileSync } from 'node:fs'; // macOS, Linux, and Windows readFileSync(''); // => [Error: EISDIR: illegal operation on a directory, read ] // FreeBSD readFileSync(''); // => ```
f
readlinkSync
Returns the symbolic link's string value. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a `Buffer` object.
f
readSync
Returns the number of `bytesRead`. For detailed information, see the documentation of the asynchronous version of this API: [read](.././node__fs.d.ts/~/read).
f
readv
Read from a file specified by `fd` and write to an array of `ArrayBufferView`s using `readv()`. `position` is the offset from the beginning of the file from where data should be read. If `typeof position !== 'number'`, the data will be read from the current position. The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. If this method is invoked as its `util.promisify()` ed version, it returns a promise for an `Object` with `bytesRead` and `buffers` properties.
f
readvSync
For detailed information, see the documentation of the asynchronous version of this API: [readv](.././node__fs.d.ts/~/readv).
f
N
realpath
Asynchronously computes the canonical pathname by resolving `.`, `..`, and symbolic links. A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames. This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: 1. No case conversion is performed on case-insensitive file systems. 2. The maximum number of symbolic links is platform-independent and generally (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path passed to the callback. If the `encoding` is set to `'buffer'`, the path returned will be passed as a `Buffer` object. If `path` resolves to a socket or a pipe, the function will return a system dependent name for that object.
f
realpath.native
Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). The `callback` gets two arguments `(err, resolvedPath)`. Only paths that can be converted to UTF8 strings are supported. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use for the path passed to the callback. If the `encoding` is set to `'buffer'`, the path returned will be passed as a `Buffer` object. On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction.
f
N
realpathSync
Returns the resolved pathname. For detailed information, see the documentation of the asynchronous version of this API: [realpath](.././node__fs.d.ts/~/realpath).
f
realpathSync.native
No documentation available
f
rename
Asynchronously rename file at `oldPath` to the pathname provided as `newPath`. In the case that `newPath` already exists, it will be overwritten. If there is a directory at `newPath`, an error will be raised instead. No arguments other than a possible exception are given to the completion callback. See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). ```js import { rename } from 'node:fs'; rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; console.log('Rename complete!'); }); ```
f
renameSync
Renames the file from `oldPath` to `newPath`. Returns `undefined`. See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details.
f
rm
Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the completion callback.
f
rmdir
Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given to the completion callback. Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [rm](.././node__fs.d.ts/~/rm) with options `{ recursive: true, force: true }`.
f
rmdirSync
Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [rmSync](.././node__fs.d.ts/~/rmSync) with options `{ recursive: true, force: true }`.
f
rmSync
Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`.
f
stat
Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. In case of an error, the `err.code` will be one of `Common System Errors`. [stat](.././node__fs.d.ts/~/stat) follows symbolic links. Use [lstat](.././node__fs.d.ts/~/lstat) to look at the links themselves. Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available. To check if a file exists without manipulating it afterwards, [access](.././node__fs.d.ts/~/access) is recommended. For example, given the following directory structure: ```text - txtDir -- file.txt - app.js ``` The next program will check for the stats of the given paths: ```js import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); } ``` The resulting output will resemble: ```console true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z } ```
f
statfs
Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. In case of an error, the `err.code` will be one of `Common System Errors`.
f
statfsSync
Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which contains `path`. In case of an error, the `err.code` will be one of `Common System Errors`.
f
symlinkSync
Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [symlink](.././node__fs.d.ts/~/symlink).
f
truncate
Truncates the file. No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, `fs.ftruncate()` is called. ```js import { truncate } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. truncate('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was truncated'); }); ``` Passing a file descriptor is deprecated and may result in an error being thrown in the future. See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details.
f
truncateSync
Truncates the file. Returns `undefined`. A file descriptor can also be passed as the first argument. In this case, `fs.ftruncateSync()` is called. Passing a file descriptor is deprecated and may result in an error being thrown in the future.
f
unlinkSync
Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`.
f
unwatchFile
Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, _all_ listeners are removed, effectively stopping watching of `filename`. Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. Using [watch](.././node__fs.d.ts/~/watch) is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible.
f
utimes
Change the file system timestamps of the object referenced by `path`. The `atime` and `mtime` arguments follow these rules: * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.
f
utimesSync
Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [utimes](.././node__fs.d.ts/~/utimes).
f
watch
Watch for changes on `filename`, where `filename` is either a file or a directory. The second argument is optional. If `options` is provided as a string, it specifies the `encoding`. Otherwise `options` should be passed as an object. The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file which triggered the event. On most platforms, `'rename'` is emitted whenever a filename appears or disappears in the directory. The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. If a `signal` is passed, aborting the corresponding AbortController will close the returned `fs.FSWatcher`.
f
watchFile
Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates whether the process should continue to run as long as files are being watched. The `options` object may specify an `interval` property indicating how often the target should be polled in milliseconds. The `listener` gets two arguments the current stat object and the previous stat object: ```js import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); }); ``` These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, the numeric values in these objects are specified as `BigInt`s. To be notified when the file was modified, not just accessed, it is necessary to compare `curr.mtimeMs` and `prev.mtimeMs`. When an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10. Using [watch](.././node__fs.d.ts/~/watch) is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. When a file being watched by `fs.watchFile()` disappears and reappears, then the contents of `previous` in the second callback event (the file's reappearance) will be the same as the contents of `previous` in the first callback event (its disappearance). This happens when: * the file is deleted, followed by a restore * the file is renamed and then renamed a second time back to its original name
f
write
Write `buffer` to the file specified by `fd`. `offset` determines the part of the buffer to be written, and `length` is an integer specifying the number of bytes to write. `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. If this method is invoked as its `util.promisify()` ed version, it returns a promise for an `Object` with `bytesWritten` and `buffer` properties. It is unsafe to use `fs.write()` multiple times on the same file without waiting for the callback. For this scenario, [createWriteStream](.././node__fs.d.ts/~/createWriteStream) is recommended. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
f
writeFile
> [!WARNING] Deno compatibility > Missing `utf16le`, `latin1` and `ucs2` encoding. When `file` is a filename, asynchronously writes data to the file, replacing the file if it already exists. `data` can be a string or a buffer. When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using a file descriptor. The `encoding` option is ignored if `data` is a buffer. The `mode` option only affects the newly created file. See [open](.././node__fs.d.ts/~/open) for more details. ```js import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, (err) => { if (err) throw err; console.log('The file has been saved!'); }); ``` If `options` is a string, then it specifies the encoding: ```js import { writeFile } from 'node:fs'; writeFile('message.txt', 'Hello Node.js', 'utf8', callback); ``` It is unsafe to use `fs.writeFile()` multiple times on the same file without waiting for the callback. For this scenario, [createWriteStream](.././node__fs.d.ts/~/createWriteStream) is recommended. Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that performs multiple `write` calls internally to write the buffer passed to it. For performance sensitive code consider using [createWriteStream](.././node__fs.d.ts/~/createWriteStream). It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. Cancelation is "best effort", and some amount of data is likely still to be written. ```js import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const controller = new AbortController(); const { signal } = controller; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, { signal }, (err) => { // When a request is aborted - the callback is called with an AbortError }); // When the request should be aborted controller.abort(); ``` Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs.
f
writeFileSync
> [!WARNING] Deno compatibility > Missing `utf16le`, `latin1` and `ucs2` encoding. Returns `undefined`. The `mode` option only affects the newly created file. See [open](.././node__fs.d.ts/~/open) for more details. For detailed information, see the documentation of the asynchronous version of this API: [writeFile](.././node__fs.d.ts/~/writeFile).
f
writeSync
For detailed information, see the documentation of the asynchronous version of this API: [write](.././node__fs.d.ts/~/write).
f
writev
Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. `position` is the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. It is unsafe to use `fs.writev()` multiple times on the same file without waiting for the callback. For this scenario, use [createWriteStream](.././node__fs.d.ts/~/createWriteStream). On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
f
writevSync
For detailed information, see the documentation of the asynchronous version of this API: [writev](.././node__fs.d.ts/~/writev).
f
exists
Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false: ```js import { exists } from 'node:fs'; exists('/etc/passwd', (e) => { console.log(e ? 'it exists' : 'no passwd!'); }); ``` **The parameters for this callback are not consistent with other Node.js** **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback has only one boolean parameter. This is one reason `fs.access()` is recommended instead of `fs.exists()`. Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist. **write (NOT RECOMMENDED)** ```js import { exists, open, close } from 'node:fs'; exists('myfile', (e) => { if (e) { console.error('myfile already exists'); } else { open('myfile', 'wx', (err, fd) => { if (err) throw err; try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); } }); ``` **write (RECOMMENDED)** ```js import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` **read (NOT RECOMMENDED)** ```js import { open, close, exists } from 'node:fs'; exists('myfile', (e) => { if (e) { open('myfile', 'r', (err, fd) => { if (err) throw err; try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); } else { console.error('myfile does not exist'); } }); ``` **read (RECOMMENDED)** ```js import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); ``` The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any. In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process.
f
lchmod
Changes the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback. This method is only implemented on macOS. See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
f
lchmodSync
Changes the permissions on a symbolic link. Returns `undefined`. This method is only implemented on macOS. See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
f
promises.lchmod
> [!WARNING] Deno compatibility > The lchmod implementation is a not implemented. Changes the permissions on a symbolic link. This method is only implemented on macOS.

Interfaces

I
BigIntOptions
No documentation available
I
I
BigIntStatsFs
No documentation available
I
CopyOptions
No documentation available
I
CopySyncOptions
No documentation available
I
CreateReadStreamFSImplementation
No documentation available
I
I
FSImplementation
No documentation available
I
GlobOptions
No documentation available
I
GlobOptionsWithFileTypes
No documentation available
I
GlobOptionsWithoutFileTypes
No documentation available
I
MakeDirectoryOptions
No documentation available
I
ObjectEncodingOptions
No documentation available
I
OpenAsBlobOptions
No documentation available
I
OpenDirOptions
No documentation available
I
promises.FileChangeInfo
No documentation available
I
promises.FileReadResult
No documentation available
I
promises.FlagAndOpenMode
No documentation available
I
promises.ReadableWebStreamOptions
No documentation available
I
ReadAsyncOptions
No documentation available
I
ReadStreamOptions
No documentation available
I
ReadSyncOptions
No documentation available
I
ReadVResult
No documentation available
I
RmDirOptions
No documentation available
I
I
StatFsOptions
No documentation available
I
StatOptions
No documentation available
c
I
Stats
A `fs.Stats` object provides information about a file. Objects returned from [stat](.././node__fs.d.ts/~/stat), [lstat](.././node__fs.d.ts/~/lstat), [fstat](.././node__fs.d.ts/~/fstat), and their synchronous counterparts are of this type. If `bigint` in the `options` passed to those methods is true, the numeric values will be `bigint` instead of `number`, and the object will contain additional nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. ```console Stats { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 527, blksize: 4096, blocks: 8, atimeMs: 1318289051000.1, mtimeMs: 1318289051000.1, ctimeMs: 1318289051000.1, birthtimeMs: 1318289051000.1, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT } ``` `bigint` version: ```console BigIntStats { dev: 2114n, ino: 48064969n, mode: 33188n, nlink: 1n, uid: 85n, gid: 100n, rdev: 0n, size: 527n, blksize: 4096n, blocks: 8n, atimeMs: 1318289051000n, mtimeMs: 1318289051000n, ctimeMs: 1318289051000n, birthtimeMs: 1318289051000n, atimeNs: 1318289051000000000n, mtimeNs: 1318289051000000000n, ctimeNs: 1318289051000000000n, birthtimeNs: 1318289051000000000n, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT } ```
c
I
StatsFs
Provides information about a mounted file system. Objects returned from [statfs](.././node__fs.d.ts/~/statfs) and its synchronous counterpart are of this type. If `bigint` in the `options` passed to those methods is `true`, the numeric values will be `bigint` instead of `number`. ```console StatFs { type: 1397114950, bsize: 4096, blocks: 121938943, bfree: 61058895, bavail: 61058895, files: 999, ffree: 1000000 } ``` `bigint` version: ```console StatFs { type: 1397114950n, bsize: 4096n, blocks: 121938943n, bfree: 61058895n, bavail: 61058895n, files: 999n, ffree: 1000000n } ```
I
StatSyncFn
No documentation available
I
StatSyncOptions
No documentation available
I
StatWatcher
Class: fs.StatWatcher
I
WatchFileOptions
Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates whether the process should continue to run as long as files are being watched. The `options` object may specify an `interval` property indicating how often the target should be polled in milliseconds. The `listener` gets two arguments the current stat object and the previous stat object: ```js import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); }); ``` These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, the numeric values in these objects are specified as `BigInt`s. To be notified when the file was modified, not just accessed, it is necessary to compare `curr.mtimeMs` and `prev.mtimeMs`. When an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10. Using [watch](.././node__fs.d.ts/~/watch) is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. When a file being watched by `fs.watchFile()` disappears and reappears, then the contents of `previous` in the second callback event (the file's reappearance) will be the same as the contents of `previous` in the first callback event (its disappearance). This happens when: * the file is deleted, followed by a restore * the file is renamed and then renamed a second time back to its original name
I
WatchOptions
No documentation available
I
WriteStreamOptions
No documentation available
I
WriteVResult
No documentation available

Namespaces

N
constants
No documentation available
N
promises
The `fs/promises` API provides asynchronous file system methods that return promises. The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.

Type Aliases

T
BigIntStatsListener
No documentation available
T
BufferEncodingOption
No documentation available
T
EncodingOption
No documentation available
T
Mode
No documentation available
T
NoParamCallback
No documentation available
T
OpenMode
No documentation available
T
PathLike
Valid types for path values in "fs".
T
PathOrFileDescriptor
No documentation available
T
ReadPosition
No documentation available
T
StatsListener
No documentation available
T
TimeLike
No documentation available
T
WatchEventType
No documentation available
T
WatchListener
No documentation available
T
WriteFileOptions
No documentation available

Variables

v
constants.COPYFILE_EXCL
Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
v
constants.COPYFILE_FICLONE
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
v
constants.COPYFILE_FICLONE_FORCE
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.
v
constants.F_OK
Constant for fs.access(). File is visible to the calling process.
v
constants.O_APPEND
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
v
constants.O_CREAT
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
v
constants.O_DIRECT
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
v
constants.O_DIRECTORY
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
v
constants.O_DSYNC
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
v
constants.O_EXCL
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
v
constants.O_NOATIME
constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
v
constants.O_NOCTTY
Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
v
constants.O_NOFOLLOW
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
v
constants.O_NONBLOCK
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
v
constants.O_RDONLY
Constant for fs.open(). Flag indicating to open a file for read-only access.
v
constants.O_RDWR
Constant for fs.open(). Flag indicating to open a file for read-write access.
v
constants.O_SYNC
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
v
constants.O_TRUNC
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
v
constants.O_WRONLY
Constant for fs.open(). Flag indicating to open a file for write-only access.
v
constants.R_OK
Constant for fs.access(). File can be read by the calling process.
v
constants.S_IFBLK
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
v
constants.S_IFCHR
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
v
constants.S_IFDIR
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
v
constants.S_IFIFO
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
v
constants.S_IFLNK
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
v
constants.S_IFMT
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
v
constants.S_IFREG
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
v
constants.S_IFSOCK
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
v
constants.S_IRGRP
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
v
constants.S_IROTH
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
v
constants.S_IRUSR
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
v
constants.S_IRWXG
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
v
constants.S_IRWXO
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
v
constants.S_IRWXU
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
v
constants.S_IWGRP
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
v
constants.S_IWOTH
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
v
constants.S_IWUSR
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
v
constants.S_IXGRP
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
v
constants.S_IXOTH
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
v
constants.S_IXUSR
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
v
constants.UV_FS_O_FILEMAP
When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.
v
constants.W_OK
Constant for fs.access(). File can be written by the calling process.
v
constants.X_OK
Constant for fs.access(). File can be executed by the calling process.
v
lstatSync
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
v
promises.constants
No documentation available
v
statSync
Synchronous stat(2) - Get file status.