fs/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.
Usage in Deno
import * as mod from "node:fs/promises";
Functions
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.
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
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.
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.
Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail.
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.
Determines the actual location of path using the same semantics as the fs.realpath.native() function.
Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.
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.
Interfaces
Variables
function access
Usage in Deno
import { access } from "node:fs/promises";
#access(path: PathLike,mode?: number,): Promise<void>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.
Parameters #
Return Type #
Promise<void> Fulfills with undefined upon success.
function appendFile
Usage in Deno
import { appendFile } from "node:fs/promises";
#appendFile(): Promise<void>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()).
Parameters #
#path: PathLike | FileHandle filename or {FileHandle}
#data: string | Uint8Array #options: ()
| BufferEncoding
| null Return Type #
Promise<void> Fulfills with undefined upon success.
function copyFile
Usage in Deno
import { copyFile } from "node:fs/promises";
#copyFile(): Promise<void>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');
}
Parameters #
#mode: number = 0 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)
Return Type #
Promise<void> Fulfills with undefined upon success.
function cp
Usage in Deno
import { cp } from "node:fs/promises";
#cp(): Promise<void>function glob
Usage in Deno
import { glob } from "node:fs/promises";
Overload 1
#glob(pattern: string | string[]): AsyncIterator<string>Overload 2
#glob(pattern: string | string[],opt: GlobOptionsWithFileTypes,): AsyncIterator<Dirent>Overload 3
#glob(pattern: string | string[],): AsyncIterator<string>Overload 4
#glob(pattern: string | string[],opt: GlobOptions,): AsyncIterator<Dirent | string>function link
Usage in Deno
import { link } from "node:fs/promises";
function lstat
Usage in Deno
import { lstat } from "node:fs/promises";
Overload 1
#lstat(path: PathLike,opts?: StatOptions & { bigint?: false | undefined; },): 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.
Parameters #
#opts: StatOptions & { bigint?: false | undefined; } Return Type #
Promise<Stats> Fulfills with the {fs.Stats} object for the given symbolic link path.
Overload 2
#lstat(path: PathLike,opts: StatOptions & { bigint: true; },): Promise<BigIntStats>Parameters #
#opts: StatOptions & { bigint: true; } Return Type #
Promise<BigIntStats> Overload 3
#lstat(path: PathLike,opts?: StatOptions,): Promise<Stats | BigIntStats>Parameters #
#opts: StatOptions Return Type #
Promise<Stats | BigIntStats> function lutimes
Usage in Deno
import { lutimes } from "node:fs/promises";
#lutimes(): Promise<void>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.
Parameters #
Return Type #
Promise<void> Fulfills with undefined upon success.
function mkdir
Usage in Deno
import { mkdir } from "node:fs/promises";
Overload 1
#mkdir(path: PathLike,options: MakeDirectoryOptions & { recursive: true; },): Promise<string | undefined>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);
}
Parameters #
#options: MakeDirectoryOptions & { recursive: true; } Return Type #
Promise<string | undefined> Upon success, fulfills with undefined if recursive is false, or the first directory path created if recursive is true.
Overload 2
#mkdir(path: PathLike,options?: ,): Promise<void>Asynchronous mkdir(2) - create a directory.
Parameters #
#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.
Return Type #
Promise<void> Overload 3
#mkdir(path: PathLike,options?: ,): Promise<string | undefined>Asynchronous mkdir(2) - create a directory.
Parameters #
#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.
Return Type #
Promise<string | undefined> function mkdtemp
Usage in Deno
import { mkdtemp } from "node:fs/promises";
Overload 1
#mkdtemp(prefix: string,options?: ,): 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').
Parameters #
Return Type #
Promise<string> Fulfills with a string containing the file system path of the newly created temporary directory.
Overload 2
#mkdtemp(prefix: string,options: BufferEncodingOption,): Promise<Buffer>Asynchronously creates a unique temporary directory.
Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
Parameters #
#prefix: string #options: BufferEncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
Promise<Buffer> Overload 3
#mkdtemp(prefix: string,options?: ,): Promise<string | Buffer>Asynchronously creates a unique temporary directory.
Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
Parameters #
Return Type #
Promise<string | Buffer> function open
Usage in Deno
import { open } from "node:fs/promises";
#open(): 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.
Parameters #
Return Type #
Promise<FileHandle> Fulfills with a {FileHandle} object.
function opendir
Usage in Deno
import { opendir } from "node:fs/promises";
#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.
Parameters #
#options: OpenDirOptions Return Type #
Promise<Dir> Fulfills with an {fs.Dir}.
function readdir
Usage in Deno
import { readdir } from "node:fs/promises";
Overload 1
#readdir(path: PathLike,options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null,): Promise<string[]>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);
}
Parameters #
#options: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null Return Type #
Promise<string[]> Fulfills with an array of the names of the files in the directory excluding '.' and '..'.
Overload 2
#readdir(path: PathLike,options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer",): Promise<Buffer[]>Asynchronous readdir(3) - read a directory.
Parameters #
#options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer" The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
Promise<Buffer[]> Overload 3
#readdir(path: PathLike,options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null,): Promise<string[] | Buffer[]>Asynchronous readdir(3) - read a directory.
Parameters #
#options: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
Promise<string[] | Buffer[]> Overload 4
#readdir(path: PathLike,options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; },): Promise<Dirent[]>Asynchronous readdir(3) - read a directory.
Parameters #
#options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; } If called with withFileTypes: true the result data will be an array of Dirent.
Return Type #
Promise<Dirent[]> function readFile
Usage in Deno
import { readFile } from "node:fs/promises";
Overload 1
#readFile(path: PathLike | FileHandle,): Promise<Buffer>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.
Parameters #
Return Type #
Promise<Buffer> Fulfills with the contents of the file.
Overload 2
#readFile(path: PathLike | FileHandle,): Promise<string>Asynchronously reads the entire contents of a file.
Parameters #
#path: PathLike | FileHandle 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.
Return Type #
Promise<string> Overload 3
#readFile(path: PathLike | FileHandle,options?: ,): Promise<string | Buffer>Asynchronously reads the entire contents of a file.
Parameters #
#path: PathLike | FileHandle 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'.
Return Type #
Promise<string | Buffer> function readlink
Usage in Deno
import { readlink } from "node:fs/promises";
Overload 1
#readlink(path: PathLike,options?: ,): 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.
Parameters #
#options: Return Type #
Promise<string> Fulfills with the linkString upon success.
Overload 2
#readlink(path: PathLike,options: BufferEncodingOption,): Promise<Buffer>Asynchronous readlink(2) - read value of a symbolic link.
Parameters #
#options: BufferEncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
Promise<Buffer> Overload 3
#readlink(path: PathLike,options?: ,): Promise<string | Buffer>function realpath
Usage in Deno
import { realpath } from "node:fs/promises";
Overload 1
#realpath(path: PathLike,options?: ,): 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.
Parameters #
#options: Return Type #
Promise<string> Fulfills with the resolved path upon success.
Overload 2
#realpath(path: PathLike,options: BufferEncodingOption,): Promise<Buffer>Asynchronous realpath(3) - return the canonicalized absolute pathname.
Parameters #
#options: BufferEncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
Promise<Buffer> Overload 3
#realpath(path: PathLike,options?: ,): Promise<string | Buffer>function rm
Usage in Deno
import { rm } from "node:fs/promises";
function rmdir
Usage in Deno
import { rmdir } from "node:fs/promises";
#rmdir(path: PathLike,options?: RmDirOptions,): Promise<void>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 }.
Parameters #
#options: RmDirOptions Return Type #
Promise<void> Fulfills with undefined upon success.
function stat
Usage in Deno
import { stat } from "node:fs/promises";
Overload 1
#stat(path: PathLike,opts?: StatOptions & { bigint?: false | undefined; },): Promise<Stats>Overload 2
#stat(path: PathLike,opts: StatOptions & { bigint: true; },): Promise<BigIntStats>Parameters #
#opts: StatOptions & { bigint: true; } Return Type #
Promise<BigIntStats> Overload 3
#stat(path: PathLike,opts?: StatOptions,): Promise<Stats | BigIntStats>Parameters #
#opts: StatOptions Return Type #
Promise<Stats | BigIntStats> function statfs
Usage in Deno
import { statfs } from "node:fs/promises";
Overload 1
#statfs(path: PathLike,opts?: StatFsOptions & { bigint?: false | undefined; },): Promise<StatsFs>Overload 2
#statfs(path: PathLike,opts: StatFsOptions & { bigint: true; },): Promise<BigIntStatsFs>Parameters #
#opts: StatFsOptions & { bigint: true; } Return Type #
Promise<BigIntStatsFs> Overload 3
#statfs(path: PathLike,opts?: StatFsOptions,): Promise<StatsFs | BigIntStatsFs>Parameters #
#opts: StatFsOptions Return Type #
Promise<StatsFs | BigIntStatsFs> function symlink
Usage in Deno
import { symlink } from "node:fs/promises";
#symlink(): Promise<void>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.
Parameters #
Return Type #
Promise<void> Fulfills with undefined upon success.
function truncate
Usage in Deno
import { truncate } from "node:fs/promises";
function unlink
Usage in Deno
import { unlink } from "node:fs/promises";
#unlink(path: PathLike): Promise<void>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.
Parameters #
Return Type #
Promise<void> Fulfills with undefined upon success.
function utimes
Usage in Deno
import { utimes } from "node:fs/promises";
#utimes(): Promise<void>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.
Parameters #
Return Type #
Promise<void> Fulfills with undefined upon success.
function watch
Usage in Deno
import { watch } from "node:fs/promises";
Overload 1
#watch(filename: PathLike,options: (WatchOptions & { encoding: "buffer"; }) | "buffer",): AsyncIterable<FileChangeInfo<Buffer>>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().
Parameters #
#options: (WatchOptions & { encoding: "buffer"; }) | "buffer" Return Type #
AsyncIterable<FileChangeInfo<Buffer>> of objects with the properties:
Overload 2
#watch(filename: PathLike,options?: WatchOptions | BufferEncoding,): AsyncIterable<FileChangeInfo<string>>Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.
Parameters #
A path to a file or directory. If a URL is provided, it must use the file: protocol.
#options: WatchOptions | BufferEncoding Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
If encoding is not supplied, the default of 'utf8' is used.
If persistent is not supplied, the default of true is used.
If recursive is not supplied, the default of false is used.
Return Type #
AsyncIterable<FileChangeInfo<string>> Overload 3
#watch(filename: PathLike,options: WatchOptions | string,): AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>>Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.
Parameters #
A path to a file or directory. If a URL is provided, it must use the file: protocol.
#options: WatchOptions | string Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
If encoding is not supplied, the default of 'utf8' is used.
If persistent is not supplied, the default of true is used.
If recursive is not supplied, the default of false is used.
Return Type #
AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>> function writeFile
Usage in Deno
import { writeFile } from "node:fs/promises";
#writeFile(file: PathLike | FileHandle,data: string
| ArrayBufferView
| Iterable<string | ArrayBufferView>
| AsyncIterable<string | ArrayBufferView>
| Stream,options?: (ObjectEncodingOptions
& { mode?: Mode | undefined; flag?: OpenMode | undefined; flush?: boolean | undefined; }
& Abortable)
| BufferEncoding
| null,): Promise<void>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.
Parameters #
#file: PathLike | FileHandle filename or FileHandle
#options: (ObjectEncodingOptions
& { mode?: Mode | undefined; flag?: OpenMode | undefined; flush?: boolean | undefined; }
& Abortable)
| BufferEncoding
| null Return Type #
Promise<void> Fulfills with undefined upon success.
interface CreateReadStreamOptions
Usage in Deno
import { type CreateReadStreamOptions } from "node:fs/promises";
interface CreateWriteStreamOptions
Usage in Deno
import { type CreateWriteStreamOptions } from "node:fs/promises";
interface FileChangeInfo
Usage in Deno
import { type FileChangeInfo } from "node:fs/promises";
interface FileHandle
Usage in Deno
import { type FileHandle } from "node:fs/promises";
Properties #
Methods #
#appendFile(data: string | Uint8Array,options?: ,): Promise<void> Alias of filehandle.writeFile().
When operating on file handles, the mode cannot be changed from what it was set
to with fsPromises.open(). Therefore, this is equivalent to filehandle.writeFile().
Changes the ownership of the file. A wrapper for chown(2).
#createReadStream(options?: CreateReadStreamOptions): ReadStream 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] range. If start is
omitted or undefined, filehandle.createReadStream() reads sequentially from
the current file position. The encoding can be any one of those accepted by Buffer.
If the FileHandle 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.
import { open } from 'node:fs/promises';
const fd = await open('/dev/input/event0');
// Create a stream from some character device.
const stream = fd.createReadStream();
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.
An example to read the last 10 bytes of a file which is 100 bytes long:
import { open } from 'node:fs/promises';
const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 });
#createWriteStream(options?: CreateWriteStreamOptions): WriteStream 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] range. Modifying a file rather than
replacing it may require the flags open option to be set to r+ rather than
the default r. 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.
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) documentation for details.
Unlike filehandle.sync this method does not flush modified metadata.
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) documentation for more detail.
#read<T extends ArrayBufferView>(buffer: T,offset?: number | null,length?: number | null,position?: number | null,): Promise<FileReadResult<T>> Reads data from the file and stores that in the given buffer.
If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
#read<T extends ArrayBufferView = Buffer>(buffer: T,options?: FileReadOptions<T>,): Promise<FileReadResult<T>> #read<T extends ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>> #readableWebStream(options?: ReadableWebStreamOptions): ReadableStream Returns a ReadableStream that may be used to read the files data.
An error will be thrown if this method is called more than once or is called
after the FileHandle is closed or closing.
import {
open,
} from 'node:fs/promises';
const file = await open('./some/file/to/read');
for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
While the ReadableStream will read the file to completion, it will not
close the FileHandle automatically. User code must still call thefileHandle.close() method.
#readFile(options?: { encoding?: null | undefined; flag?: OpenMode | undefined; } | null): Promise<Buffer> Asynchronously reads the entire contents of a file.
If options is a string, then it specifies the encoding.
The FileHandle has to support reading.
If one or more filehandle.read() calls are made on a file handle and then a filehandle.readFile() call is made, the data will be read from the current
position till the end of the file. It doesn't always read from the beginning
of the file.
#readFile(options: { encoding: BufferEncoding; flag?: OpenMode | undefined; } | BufferEncoding): Promise<string> Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically.
The FileHandle must have been opened for reading.
Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically.
The FileHandle must have been opened for reading.
#readLines(options?: CreateReadStreamOptions): ReadlineInterface Convenience method to create a readline interface and stream over the file.
See filehandle.createReadStream() for the options.
import { open } from 'node:fs/promises';
const file = await open('./some/file/to/read');
for await (const line of file.readLines()) {
console.log(line);
}
#stat(opts?: StatOptions & { bigint?: false | undefined; }): Promise<Stats> #stat(opts: StatOptions & { bigint: true; }): Promise<BigIntStats> #stat(opts?: StatOptions): Promise<Stats | BigIntStats> Truncates the file.
If the file was larger than len bytes, only the first len bytes will be
retained in the file.
The following example retains only the first four bytes of the file:
import { open } from 'node:fs/promises';
let filehandle = null;
try {
filehandle = await open('temp.txt', 'r+');
await filehandle.truncate(4);
} finally {
await filehandle?.close();
}
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.
Change the file system timestamps of the object referenced by the FileHandle then fulfills the promise with no arguments upon success.
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 promise is fulfilled with no arguments upon success.
If options is a string, then it specifies the encoding.
The FileHandle has to support writing.
It is unsafe to use filehandle.writeFile() multiple times on the same file
without waiting for the promise to be fulfilled (or rejected).
If one or more filehandle.write() calls are made on a file handle and then afilehandle.writeFile() call is made, the data will be written from the
current position till the end of the file. It doesn't always write from the
beginning of the file.
#write<TBuffer extends Uint8Array>(buffer: TBuffer,offset?: number | null,length?: number | null,position?: number | null,): Promise<{ bytesWritten: number; buffer: TBuffer; }> Write buffer to the file.
The promise is fulfilled with an object containing two properties:
It is unsafe to use filehandle.write() multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use filehandle.createWriteStream().
On Linux, positional writes do not 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.
#writev(buffers: readonly ArrayBufferView[],position?: number,): Promise<WriteVResult> Write an array of ArrayBufferView s to the file.
The promise is fulfilled with an object containing a two properties:
It is unsafe to call writev() multiple times on the same file without waiting
for the promise to be fulfilled (or rejected).
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.
#readv(buffers: readonly ArrayBufferView[],position?: number,): Promise<ReadVResult> Read from a file and write to an array of ArrayBufferView s
Closes the file handle after waiting for any pending operation on the handle to complete.
import { open } from 'node:fs/promises';
let filehandle;
try {
filehandle = await open('thefile.txt', 'r');
} finally {
await filehandle?.close();
}
#[[Symbol.asyncDispose]](): Promise<void> An alias for FileHandle.close().
interface ReadableWebStreamOptions
Usage in Deno
import { type ReadableWebStreamOptions } from "node:fs/promises";