Promises
[<Interface>]
type Promises =
abstract member constants: Constants2
abstract member ``open`` (path: PathLike, ?flags: OpenMode, ?mode: OpenMode) : Promise<FileHandle>
abstract member access (path: PathLike, ?mode: float) : Promise<unit>
abstract member appendFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, data: U15<string,AsyncIterable<BinaryLike,obj,obj>,BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Iterable<BinaryLike,obj,obj>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,Options>) : Promise<unit>
abstract member chmod (path: PathLike, mode: Mode) : Promise<unit>
abstract member chown (path: PathLike, uid: float, gid: float) : Promise<unit>
abstract member copyFile (src: PathLike, dest: PathLike, ?mode: float) : Promise<unit>
abstract member cp (source: U2<string,URL>, destination: U2<string,URL>, ?opts: CopyOptions) : Promise<unit>
abstract member glob (pattern: U2<string,string array>, options: GlobOptions) : AsyncIterator<U2<string,Dirent<string>>,obj,obj>
abstract member glob (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes) : AsyncIterator<string,obj,obj>
abstract member glob (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes) : AsyncIterator<Dirent<string>,obj,obj>
abstract member glob (pattern: U2<string,string array>) : AsyncIterator<string,obj,obj>
abstract member lchmod (path: PathLike, mode: Mode) : Promise<unit>
abstract member lchown (path: PathLike, uid: float, gid: float) : Promise<unit>
abstract member link (existingPath: PathLike, newPath: PathLike) : Promise<unit>
abstract member lstat (path: PathLike, ?opts: StatOptions) : Promise<U2<BigIntStats,Stats>>
abstract member lstat (path: PathLike, opts: Opts2) : Promise<BigIntStats>
abstract member lstat (path: PathLike, ?opts: Opts) : Promise<Stats>
abstract member lutimes (path: PathLike, atime: TimeLike, mtime: TimeLike) : Promise<unit>
abstract member mkdir (path: PathLike, ?options: U3<string,float,MakeDirectoryOptions>) : Promise<string option>
abstract member mkdir (path: PathLike, ?options: U3<string,float,Options2>) : Promise<unit>
abstract member mkdir (path: PathLike, options: Options) : Promise<string option>
abstract member mkdtemp (prefix: string, options: BufferEncodingOption) : Promise<NonSharedBuffer>
abstract member mkdtemp (prefix: string, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>
abstract member opendir (path: PathLike, ?options: OpenDirOptions) : Promise<Dir>
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, ?options: U2<string,Options3>) : Promise<U2<string,NonSharedBuffer>>
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, options: U2<string,Options2>) : Promise<string>
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, ?options: Options) : Promise<NonSharedBuffer>
abstract member readdir (path: PathLike, options: Options5) : Promise<Dirent<NonSharedBuffer> array>
abstract member readdir (path: PathLike, options: Options4) : Promise<Dirent<string> array>
abstract member readdir (path: PathLike, ?options: U2<string,Options3>) : Promise<U2<string array,NonSharedBuffer array>>
abstract member readdir (path: PathLike, options: U2<string,Options2>) : Promise<NonSharedBuffer array>
abstract member readdir (path: PathLike, ?options: U2<string,Options>) : Promise<string array>
abstract member readlink (path: PathLike, options: BufferEncodingOption) : Promise<NonSharedBuffer>
abstract member readlink (path: PathLike, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>
abstract member realpath (path: PathLike, options: BufferEncodingOption) : Promise<NonSharedBuffer>
abstract member realpath (path: PathLike, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>
abstract member rename (oldPath: PathLike, newPath: PathLike) : Promise<unit>
abstract member rm (path: PathLike, ?options: RmOptions) : Promise<unit>
abstract member rmdir (path: PathLike, ?options: RmDirOptions) : Promise<unit>
abstract member stat (path: PathLike, ?opts: StatOptions) : Promise<U2<BigIntStats,Stats>>
abstract member stat (path: PathLike, opts: Opts2) : Promise<BigIntStats>
abstract member stat (path: PathLike, ?opts: Opts) : Promise<Stats>
abstract member statfs (path: PathLike, ?opts: StatFsOptions) : Promise<U2<BigIntStatsFs,StatsFs>>
abstract member statfs (path: PathLike, opts: Opts2) : Promise<BigIntStatsFs>
abstract member statfs (path: PathLike, ?opts: Opts) : Promise<StatsFs>
abstract member symlink (target: PathLike, path: PathLike, ?type: string) : Promise<unit>
abstract member truncate (path: PathLike, ?len: float) : Promise<unit>
abstract member unlink (path: PathLike) : Promise<unit>
abstract member utimes (path: PathLike, atime: TimeLike, mtime: TimeLike) : Promise<unit>
abstract member watch (filename: PathLike, options: U2<string,WatchOptions>) : AsyncIterator<FileChangeInfo<U2<string,NonSharedBuffer>>,obj,obj>
abstract member watch (filename: PathLike, options: U2<string,WatchOptionsWithBufferEncoding>) : AsyncIterator<FileChangeInfo<NonSharedBuffer>,obj,obj>
abstract member watch (filename: PathLike, ?options: U2<string,WatchOptionsWithStringEncoding>) : AsyncIterator<FileChangeInfo<string>,obj,obj>
abstract member writeFile (file: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, data: U15<string,AsyncIterable<BinaryLike,obj,obj>,BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Iterable<BinaryLike,obj,obj>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,Options>) : Promise<unit>| Assembly | Xantham.Fable.Node |
node:fs/promises
Declared inside
Properties
abstract member constants: Constants2Methods
abstract member ``open`` (path: PathLike, ?flags: OpenMode, ?mode: OpenMode) : Promise<FileHandle>
abstract member ``open`` (path: PathLike, ?flags: OpenMode, ?mode: OpenMode) : Promise<FileHandle>Opens a FileHandle.
Refer to the POSIX open(2) documentation for more detail.
Some characters (< > : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.
@since v10.0.0
| Parameter | |
|---|---|
flags | See support of file system flags``. |
mode | Sets the file mode (permission and sticky bits) if the file is created. |
Returns. Fulfills with a object.
abstract member access (path: PathLike, ?mode: float) : Promise<unit>
abstract member access (path: PathLike, ?mode: float) : Promise<unit>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 object. The following example checks if the file/etc/passwd can be read and written by the current process.
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.
@since v10.0.0
Returns. Fulfills with undefined upon success.
abstract member appendFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, data: U15<string,AsyncIterable<BinaryLike,obj,obj>,BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Iterable<BinaryLike,obj,obj>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,Options>) : Promise<unit>
abstract member appendFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, data: U15<string,AsyncIterable<BinaryLike,obj,obj>,BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Iterable<BinaryLike,obj,obj>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,Options>) : Promise<unit>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()).
@since v10.0.0
| Parameter | |
|---|---|
path | filename or |
Returns. Fulfills with undefined upon success.
abstract member copyFile (src: PathLike, dest: PathLike, ?mode: float) : Promise<unit>
abstract member copyFile (src: PathLike, dest: PathLike, ?mode: float) : Promise<unit>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.
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');
}
@since v10.0.0
| Parameter | |
|---|---|
src | source filename to copy |
dest | destination filename of the copy operation |
mode | Optional modifiers that specify 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) |
Returns. Fulfills with undefined upon success.
abstract member cp (source: U2<string,URL>, destination: U2<string,URL>, ?opts: CopyOptions) : Promise<unit>
abstract member cp (source: U2<string,URL>, destination: U2<string,URL>, ?opts: CopyOptions) : Promise<unit>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/.
@since v16.7.0
| Parameter | |
|---|---|
src | source path to copy. |
dest | destination path to copy to. |
Returns. Fulfills with undefined upon success.
abstract member glob (pattern: U2<string,string array>, options: GlobOptions) : AsyncIterator<U2<string,Dirent<string>>,obj,obj>
abstract member glob (pattern: U2<string,string array>, options: GlobOptions) : AsyncIterator<U2<string,Dirent<string>>,obj,obj>import { glob } from 'node:fs/promises';
for await (const entry of glob('*.js'))
console.log(entry);
@since v22.0.0
Returns. An AsyncIterator that yields the paths of files that match the pattern.
abstract member glob (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes) : AsyncIterator<string,obj,obj>
abstract member glob (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes) : AsyncIterator<string,obj,obj>import { glob } from 'node:fs/promises';
for await (const entry of glob('*.js'))
console.log(entry);
@since v22.0.0
Returns. An AsyncIterator that yields the paths of files that match the pattern.
abstract member glob (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes) : AsyncIterator<Dirent<string>,obj,obj>
abstract member glob (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes) : AsyncIterator<Dirent<string>,obj,obj>import { glob } from 'node:fs/promises';
for await (const entry of glob('*.js'))
console.log(entry);
@since v22.0.0
Returns. An AsyncIterator that yields the paths of files that match the pattern.
abstract member glob (pattern: U2<string,string array>) : AsyncIterator<string,obj,obj>
abstract member glob (pattern: U2<string,string array>) : AsyncIterator<string,obj,obj>import { glob } from 'node:fs/promises';
for await (const entry of glob('*.js'))
console.log(entry);
@since v22.0.0
Returns. An AsyncIterator that yields the paths of files that match the pattern.
abstract member lstat (path: PathLike, ?opts: StatOptions) : Promise<U2<BigIntStats,Stats>>
abstract member lstat (path: PathLike, ?opts: StatOptions) : Promise<U2<BigIntStats,Stats>>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) document for more detail.
@since v10.0.0
Returns. Fulfills with the object for the given symbolic link path.
abstract member lstat (path: PathLike, opts: Opts2) : Promise<BigIntStats>
abstract member lstat (path: PathLike, opts: Opts2) : Promise<BigIntStats>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) document for more detail.
@since v10.0.0
Returns. Fulfills with the object for the given symbolic link path.
abstract member lstat (path: PathLike, ?opts: Opts) : Promise<Stats>
abstract member lstat (path: PathLike, ?opts: Opts) : Promise<Stats>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) document for more detail.
@since v10.0.0
Returns. Fulfills with the object for the given symbolic link path.
abstract member lutimes (path: PathLike, atime: TimeLike, mtime: TimeLike) : Promise<unit>
abstract member lutimes (path: PathLike, atime: TimeLike, mtime: TimeLike) : Promise<unit>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.
@since v14.5.0, v12.19.0
Returns. Fulfills with undefined upon success.
abstract member mkdir (path: PathLike, ?options: U3<string,float,MakeDirectoryOptions>) : Promise<string option>
abstract member mkdir (path: PathLike, ?options: U3<string,float,MakeDirectoryOptions>) : Promise<string option>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.
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);
}
Asynchronous mkdir(2) - create a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
abstract member mkdir (path: PathLike, ?options: U3<string,float,Options2>) : Promise<unit>
abstract member mkdir (path: PathLike, ?options: U3<string,float,Options2>) : Promise<unit>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.
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);
}
Asynchronous mkdir(2) - create a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
abstract member mkdir (path: PathLike, options: Options) : Promise<string option>
abstract member mkdir (path: PathLike, options: Options) : Promise<string option>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.
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);
}
Asynchronous mkdir(2) - create a directory.
@since v10.0.0
Returns. Upon success, fulfills with undefined if recursive is false, or the first directory path created if recursive is true.
abstract member mkdtemp (prefix: string, options: BufferEncodingOption) : Promise<NonSharedBuffer>
abstract member mkdtemp (prefix: string, options: BufferEncodingOption) : Promise<NonSharedBuffer>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.
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'). Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
| Parameter | |
|---|---|
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
abstract member mkdtemp (prefix: string, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>
abstract member mkdtemp (prefix: string, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>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.
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'). Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@since v10.0.0
Returns. Fulfills with a string containing the file system path of the newly created temporary directory.
abstract member opendir (path: PathLike, ?options: OpenDirOptions) : Promise<Dir>
abstract member opendir (path: PathLike, ?options: OpenDirOptions) : Promise<Dir>Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) 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:
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.
@since v12.12.0
Returns. Fulfills with an .
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, ?options: U2<string,Options3>) : Promise<U2<string,NonSharedBuffer>>
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, ?options: U2<string,Options3>) : Promise<U2<string,NonSharedBuffer>>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:
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:
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. Asynchronously reads the entire contents of a file.
| Parameter | |
|---|---|
path | filename or FileHandle |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. |
options | An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. |
options | An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'. |
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, options: U2<string,Options2>) : Promise<string>
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, options: U2<string,Options2>) : Promise<string>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:
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:
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. Asynchronously reads the entire contents of a file.
| Parameter | |
|---|---|
path | filename or FileHandle |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. |
options | An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. |
options | An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'. |
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, ?options: Options) : Promise<NonSharedBuffer>
abstract member readFile (path: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, ?options: Options) : Promise<NonSharedBuffer>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:
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:
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. Asynchronously reads the entire contents of a file.
@since v10.0.0
| Parameter | |
|---|---|
path | filename or FileHandle |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. |
options | An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. |
options | An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'. |
Returns. Fulfills with the contents of the file.
abstract member readdir (path: PathLike, options: Options5) : Promise<Dirent<NonSharedBuffer> array>
abstract member readdir (path: PathLike, options: Options5) : Promise<Dirent<NonSharedBuffer> array>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.
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);
}
Asynchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a directory. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
abstract member readdir (path: PathLike, options: Options4) : Promise<Dirent<string> array>
abstract member readdir (path: PathLike, options: Options4) : Promise<Dirent<string> array>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.
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);
}
Asynchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a directory. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
abstract member readdir (path: PathLike, ?options: U2<string,Options3>) : Promise<U2<string array,NonSharedBuffer array>>
abstract member readdir (path: PathLike, ?options: U2<string,Options3>) : Promise<U2<string array,NonSharedBuffer array>>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.
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);
}
Asynchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a directory. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
abstract member readdir (path: PathLike, options: U2<string,Options2>) : Promise<NonSharedBuffer array>
abstract member readdir (path: PathLike, options: U2<string,Options2>) : Promise<NonSharedBuffer array>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.
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);
}
Asynchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a directory. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
abstract member readdir (path: PathLike, ?options: U2<string,Options>) : Promise<string array>
abstract member readdir (path: PathLike, ?options: U2<string,Options>) : Promise<string array>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.
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);
}
Asynchronous readdir(3) - read a directory.
@since v10.0.0
Returns. Fulfills with an array of the names of the files in the directory excluding '.' and '..'.
abstract member readlink (path: PathLike, options: BufferEncodingOption) : Promise<NonSharedBuffer>
abstract member readlink (path: PathLike, options: BufferEncodingOption) : Promise<NonSharedBuffer>Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is fulfilled with thelinkString upon success.
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. Asynchronous readlink(2) - read value of a symbolic link.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
abstract member readlink (path: PathLike, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>
abstract member readlink (path: PathLike, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is fulfilled with thelinkString upon success.
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. Asynchronous readlink(2) - read value of a symbolic link.
@since v10.0.0
Returns. Fulfills with the linkString upon success.
abstract member realpath (path: PathLike, options: BufferEncodingOption) : Promise<NonSharedBuffer>
abstract member realpath (path: PathLike, options: BufferEncodingOption) : Promise<NonSharedBuffer>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. Asynchronous realpath(3) - return the canonicalized absolute pathname.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
abstract member realpath (path: PathLike, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>
abstract member realpath (path: PathLike, ?options: U2<string,ObjectEncodingOptions>) : Promise<string>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. Asynchronous realpath(3) - return the canonicalized absolute pathname.
@since v10.0.0
Returns. Fulfills with the resolved path upon success.
abstract member rmdir (path: PathLike, ?options: RmDirOptions) : Promise<unit>
abstract member rmdir (path: PathLike, ?options: RmDirOptions) : Promise<unit>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 }.
@since v10.0.0
Returns. Fulfills with undefined upon success.
abstract member stat (path: PathLike, ?opts: StatOptions) : Promise<U2<BigIntStats,Stats>>
abstract member stat (path: PathLike, ?opts: StatOptions) : Promise<U2<BigIntStats,Stats>>@since v10.0.0
Returns. Fulfills with the object for the given path.
abstract member stat (path: PathLike, opts: Opts2) : Promise<BigIntStats>
abstract member stat (path: PathLike, opts: Opts2) : Promise<BigIntStats>@since v10.0.0
Returns. Fulfills with the object for the given path.
abstract member statfs (path: PathLike, ?opts: StatFsOptions) : Promise<U2<BigIntStatsFs,StatsFs>>
abstract member statfs (path: PathLike, ?opts: StatFsOptions) : Promise<U2<BigIntStatsFs,StatsFs>>@since v19.6.0, v18.15.0
Returns. Fulfills with the object for the given path.
abstract member statfs (path: PathLike, opts: Opts2) : Promise<BigIntStatsFs>
abstract member statfs (path: PathLike, opts: Opts2) : Promise<BigIntStatsFs>@since v19.6.0, v18.15.0
Returns. Fulfills with the object for the given path.
abstract member symlink (target: PathLike, path: PathLike, ?type: string) : Promise<unit>
abstract member symlink (target: PathLike, path: PathLike, ?type: string) : Promise<unit>Creates a symbolic link.
The type argument is only used on Windows platforms and can be one of 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', the target argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.
@since v10.0.0
Returns. Fulfills with undefined upon success.
abstract member unlink (path: PathLike) : Promise<unit>
abstract member unlink (path: PathLike) : Promise<unit>If path refers to a symbolic link, then the link is removed without affecting the file or directory to which that link refers. If the path refers to a file path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail.
@since v10.0.0
Returns. Fulfills with undefined upon success.
abstract member utimes (path: PathLike, atime: TimeLike, mtime: TimeLike) : Promise<unit>
abstract member utimes (path: PathLike, atime: TimeLike, mtime: TimeLike) : Promise<unit>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,
Dates, or a numeric string like'123456789.0'. - If the value can not be converted to a number, or is
NaN,Infinity, or-Infinity, anErrorwill be thrown.
@since v10.0.0
Returns. Fulfills with undefined upon success.
abstract member watch (filename: PathLike, options: U2<string,WatchOptions>) : AsyncIterator<FileChangeInfo<U2<string,NonSharedBuffer>>,obj,obj>
abstract member watch (filename: PathLike, options: U2<string,WatchOptions>) : AsyncIterator<FileChangeInfo<U2<string,NonSharedBuffer>>,obj,obj>Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.
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().
@since v15.9.0, v14.18.0
Returns. of objects with the properties:
abstract member watch (filename: PathLike, options: U2<string,WatchOptionsWithBufferEncoding>) : AsyncIterator<FileChangeInfo<NonSharedBuffer>,obj,obj>
abstract member watch (filename: PathLike, options: U2<string,WatchOptionsWithBufferEncoding>) : AsyncIterator<FileChangeInfo<NonSharedBuffer>,obj,obj>Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.
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().
@since v15.9.0, v14.18.0
Returns. of objects with the properties:
abstract member watch (filename: PathLike, ?options: U2<string,WatchOptionsWithStringEncoding>) : AsyncIterator<FileChangeInfo<string>,obj,obj>
abstract member watch (filename: PathLike, ?options: U2<string,WatchOptionsWithStringEncoding>) : AsyncIterator<FileChangeInfo<string>,obj,obj>Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.
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().
@since v15.9.0, v14.18.0
Returns. of objects with the properties:
abstract member writeFile (file: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, data: U15<string,AsyncIterable<BinaryLike,obj,obj>,BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Iterable<BinaryLike,obj,obj>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,Options>) : Promise<unit>
abstract member writeFile (file: U4<string,Buffer<U2<ArrayBuffer,SharedArrayBuffer>>,FileHandle,URL>, data: U15<string,AsyncIterable<BinaryLike,obj,obj>,BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Iterable<BinaryLike,obj,obj>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,Options>) : Promise<unit>Asynchronously writes data to a file, replacing the file if it already exists. data can be a string, a buffer, an AsyncIterable, or an Iterable 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.
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.
@since v10.0.0
| Parameter | |
|---|---|
file | filename or FileHandle |
Returns. Fulfills with undefined upon success.