Optional
mode: numberFulfills with undefined
upon success.
v10.0.0
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()
).
filename or {FileHandle}
Optional
options: null | ObjectEncodingOptions & FlagAndOpenMode | BufferEncodingFulfills with undefined
upon success.
v10.0.0
Changes the ownership of a file.
Fulfills with undefined
upon success.
v10.0.0
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.
Optional
opts: StatOptions & { Fulfills with the {fs.Stats} object for the given symbolic link path
.
v10.0.0
Optional
opts: StatOptionsAsynchronously 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. CallingfsPromises.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);
}
Upon success, fulfills with undefined
if recursive
is false
, or the first directory path created if recursive
is true
.
v10.0.0
Asynchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file:
protocol.
Optional
options: null | Mode | MakeDirectoryOptions & { 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
.
Asynchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file:
protocol.
Optional
options: null | MakeDirectoryOptions | ModeEither 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
.
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
, theprefix
must end with a trailing
platform-specific path separator
(require('node:path').sep
).
Optional
options: null | ObjectEncodingOptions | BufferEncodingFulfills with a string containing the file system path of the newly created temporary directory.
v10.0.0
Asynchronously creates a unique temporary directory.
Generates six random characters to be appended behind a required prefix
to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8'
is used.
Asynchronously creates a unique temporary directory.
Generates six random characters to be appended behind a required prefix
to create a unique temporary directory.
Optional
options: null | ObjectEncodingOptions | BufferEncodingThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8'
is used.
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.
Fulfills with a {FileHandle} object.
v10.0.0
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.
filename or FileHandle
Optional
options: null | { Fulfills with the contents of the file.
v10.0.0
Asynchronously reads the entire contents of a file.
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.
An object that may contain an optional flag.
If a flag is not provided, it defaults to 'r'
.
Asynchronously reads the entire contents of a file.
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.
Optional
options: null | BufferEncoding | ObjectEncodingOptions & Abortable & { An object that may contain an optional flag.
If a flag is not provided, it defaults to 'r'
.
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 resolved 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);
}
Optional
options: null | BufferEncoding | ObjectEncodingOptions & { Fulfills with an array of the names of the files in the directory excluding '.'
and '..'
.
v10.0.0
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file:
protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8'
is used.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file:
protocol.
Optional
options: null | BufferEncoding | ObjectEncodingOptions & { The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8'
is used.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file:
protocol.
If called with withFileTypes: true
the result data will be an array of Dirent.
Reads the contents of the symbolic link referred to by path
. See the POSIX readlink(2)
documentation for more detail. The promise is
resolved 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.
Optional
options: null | ObjectEncodingOptions | BufferEncodingFulfills with the linkString
upon success.
v10.0.0
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file:
protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8'
is used.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file:
protocol.
Optional
options: null | string | ObjectEncodingOptionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8'
is used.
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 }
.
Optional
options: RmDirOptionsFulfills with undefined
upon success.
v10.0.0
Optional
opts: StatOptions & { Fulfills with the {fs.Stats} object for the given path
.
v10.0.0
Optional
opts: StatOptionsCreates 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.
Fulfills with undefined
upon success.
v10.0.0
Truncates (shortens or extends the length) of the content at path
to len
bytes.
Optional
len: numberFulfills with undefined
upon success.
v10.0.0
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.
Fulfills with undefined
upon success.
v10.0.0
Change the file system timestamps of the object referenced by path
.
The atime
and mtime
arguments follow these rules:
Date
s, or a
numeric string like '123456789.0'
.NaN
, Infinity
, or-Infinity
, an Error
will be thrown.Fulfills with undefined
upon success.
v10.0.0
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.
filename or FileHandle
Optional
options: null | BufferEncoding | ObjectEncodingOptions & { Fulfills with undefined
upon success.
v10.0.0
Generated using TypeDoc
Tests a user's permissions for the file or directory specified by
path
. Themode
argument is an optional integer that specifies the accessibility checks to be performed.mode
should be either the valuefs.constants.F_OK
or a mask consisting of the bitwise OR of any offs.constants.R_OK
,fs.constants.W_OK
, andfs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK
). CheckFile access constants
for possible values ofmode
.If the accessibility check is successful, the promise is resolved 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.Using
fsPromises.access()
to check for the accessibility of a file before callingfsPromises.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.