fs
The node:fs module enables interacting with the file system in a
way modeled on standard POSIX functions.
To use the promise-based APIs:
import * as fs from 'node:fs/promises';
To use the callback and sync APIs:
import * as fs from 'node:fs';
All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
Usage in Deno
import * as mod from "node:fs";
Classes
A representation of a directory entry, which can be a file or a subdirectory
within the directory, as returned by reading from an fs.Dir. The
directory entry is a combination of the file name and file type pairs.
Instances of fs.ReadStream are created and returned using the createReadStream function.
stream.WritableFunctions
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.
Synchronously tests a user's permissions for the file or directory specified
by path. The mode argument is an optional integer that specifies the
accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and
fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Synchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.
Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.
Asynchronously copies src to dest. By default, dest is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.
Synchronously copies src to dest. By default, dest is overwritten if it
already exists. Returns undefined. Node.js makes no guarantees about the
atomicity of the copy operation. If an error occurs after the destination file
has been opened for writing, Node.js will attempt to remove the destination.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Synchronously copies the entire directory structure from src to dest,
including subdirectories and files.
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 fd is specified and start is
omitted or undefined, fs.createReadStream() reads sequentially from the
current file position. The encoding can be any one of those accepted by Buffer.
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 option to be set to r+ rather than the
default w. The encoding can be any one of those accepted by Buffer.
Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback.
Sets the owner of the file. No arguments other than a possible exception are given to the completion callback.
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. No arguments other
than a possible
exception are given to the completion callback.
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. Returns undefined.
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. No arguments other
than a possible exception are given to the completion callback.
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback.
Retrieves the fs.Stats for the symbolic link referred to by the path.
The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
Change the file system timestamps of the symbolic link referenced by path.
Returns undefined, or throws an exception when parameters are incorrect or
the operation fails. This is the synchronous version of lutimes.
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 src to dest. By default, dest is overwritten if it
already exists.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail.
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.
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.
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.
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.
Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
Reads the contents of the symbolic link referred to by path. The callback gets
two arguments (err, linkString).
Asynchronously rename file at oldPath to the pathname provided
as newPath. In the case that newPath already exists, it will
be overwritten. If there is a directory at newPath, an error will
be raised instead. No arguments other than a possible exception are
given to the completion callback.
Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the
completion callback.
Synchronously removes files and directories (modeled on the standard POSIX rm utility). Returns undefined.
Synchronous statfs(2). Returns information about the mounted file system which
contains path.
Creates the link called path pointing to target. No arguments other than a
possible exception are given to the completion callback.
Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, fs.ftruncate() is called.
Truncates the file. Returns undefined. A file descriptor can also be
passed as the first argument. In this case, fs.ftruncateSync() is called.
Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
Stop watching for changes on filename. If listener is specified, only that
particular listener is removed. Otherwise, all listeners are removed,
effectively stopping watching of filename.
Watch for changes on filename. The callback listener will be called each
time the file is accessed.
For detailed information, see the documentation of the asynchronous version of this API: writev.
Test whether or not the given path exists by checking with the file system.
Then call the callback argument with either true or false:
Changes the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback.
Interfaces
Watch for changes on filename. The callback listener will be called each
time the file is accessed.
Namespaces
Type Aliases
string & {} allows to allow any kind of strings for the event but still allows to have auto completion for the normal events.
The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted.
The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted.
Variables
Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.
class Dir
Usage in Deno
import { Dir } from "node:fs";
A class representing a directory stream.
Created by opendir, opendirSync, or fsPromises.opendir().
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.
Properties #
The read-only path of this directory as was provided to opendir,opendirSync, or fsPromises.opendir().
Methods #
#[Symbol.asyncIterator](): AsyncIterator<Dirent> Asynchronously iterates over the directory via readdir(3) until all entries have been read.
Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors.
A promise is returned that will be fulfilled after the resource has been closed.
#close(cb: NoParamCallback): void Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors.
Asynchronously read the next directory entry via readdir(3) as an fs.Dirent.
A promise is returned that will be fulfilled with an fs.Dirent, or null if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
Synchronously read the next directory entry as an fs.Dirent. See the
POSIX readdir(3) documentation for more detail.
If there are no more directory entries to read, null will be returned.
Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
class Dirent
Usage in Deno
import { Dirent } from "node:fs";
A representation of a directory entry, which can be a file or a subdirectory
within the directory, as returned by reading from an fs.Dir. The
directory entry is a combination of the file name and file type pairs.
Additionally, when readdir or readdirSync is called with
the withFileTypes option set to true, the resulting array is filled with fs.Dirent objects, rather than strings or Buffer s.
Properties #
The file name that this fs.Dirent object refers to. The type of this
value is determined by the options.encoding passed to readdir or readdirSync.
#parentPath: string The base path that this fs.Dirent object refers to.
Methods #
#isBlockDevice(): boolean Returns true if the fs.Dirent object describes a block device.
#isCharacterDevice(): boolean Returns true if the fs.Dirent object describes a character device.
#isDirectory(): boolean Returns true if the fs.Dirent object describes a file system
directory.
#isSymbolicLink(): boolean Returns true if the fs.Dirent object describes a symbolic link.
class ReadStream
Usage in Deno
import { ReadStream } from "node:fs";
Instances of fs.ReadStream are created and returned using the createReadStream function.
Properties #
The path to the file the stream is reading from as specified in the first
argument to fs.createReadStream(). If path is passed as a string, thenreadStream.path will be a string. If path is passed as a Buffer, thenreadStream.path will be a
Buffer. If fd is specified, thenreadStream.path will be undefined.
Methods #
#addListener<K extends keyof ReadStreamEvents>(event: K,listener: ReadStreamEvents[K],): this events.EventEmitter
- open
- close
- ready
#on<K extends keyof ReadStreamEvents>(event: K,listener: ReadStreamEvents[K],): this #once<K extends keyof ReadStreamEvents>(event: K,listener: ReadStreamEvents[K],): this #prependListener<K extends keyof ReadStreamEvents>(event: K,listener: ReadStreamEvents[K],): this #prependOnceListener<K extends keyof ReadStreamEvents>(event: K,listener: ReadStreamEvents[K],): this class WriteStream
Usage in Deno
import { WriteStream } from "node:fs";
- Extends
stream.Writable
Instances of fs.WriteStream are created and returned using the createWriteStream function.
Properties #
#bytesWritten: number The number of bytes written so far. Does not include data that is still queued for writing.
The path to the file the stream is writing to as specified in the first
argument to createWriteStream. If path is passed as a string, thenwriteStream.path will be a string. If path is passed as a Buffer, thenwriteStream.path will be a
Buffer.
Methods #
#addListener<K extends keyof WriteStreamEvents>(event: K,listener: WriteStreamEvents[K],): this events.EventEmitter
- open
- close
- ready
Closes writeStream. Optionally accepts a
callback that will be executed once the writeStreamis closed.
#on<K extends keyof WriteStreamEvents>(event: K,listener: WriteStreamEvents[K],): this #once<K extends keyof WriteStreamEvents>(event: K,listener: WriteStreamEvents[K],): this #prependListener<K extends keyof WriteStreamEvents>(event: K,listener: WriteStreamEvents[K],): this #prependOnceListener<K extends keyof WriteStreamEvents>(event: K,listener: WriteStreamEvents[K],): this function access
Usage in Deno
import { access } from "node:fs";
Overload 1
#access(): voidTests a user's permissions for the file or directory specified by path.
The mode argument is an optional integer that specifies the accessibility
checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
The final argument, callback, is a callback function that is invoked with
a possible error argument. If any of the accessibility checks fail, the error
argument will be an Error object. The following examples check if package.json exists, and if it is readable or writable.
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile(), or fs.writeFile(). Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file is not accessible.
write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to
a file or directory. The fs.access() function, however, does not check the
ACL and therefore may report that a path is accessible even if the ACL restricts
the user from reading or writing to it.
Parameters #
Return Type #
void Overload 2
#access(path: PathLike,callback: NoParamCallback,): voidfunction accessSync
Usage in Deno
import { accessSync } from "node:fs";
#accessSync(path: PathLike,mode?: number,): voidSynchronously tests a user's permissions for the file or directory specified
by path. The mode argument is an optional integer that specifies the
accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and
fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for
possible values of mode.
If any of the accessibility checks fail, an Error will be thrown. Otherwise,
the method will return undefined.
import { accessSync, constants } from 'node:fs';
try {
accessSync('etc/passwd', constants.R_OK | constants.W_OK);
console.log('can read/write');
} catch (err) {
console.error('no access!');
}
Parameters #
Return Type #
void function appendFile
Usage in Deno
import { appendFile } from "node:fs";
Overload 1
#appendFile(path: PathOrFileDescriptor,data: string | Uint8Array,options: WriteFileOptions,callback: NoParamCallback,): voidAsynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
The path may be specified as a numeric file descriptor that has been opened
for appending (using fs.open() or fs.openSync()). The file descriptor will
not be closed automatically.
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
Parameters #
#path: PathOrFileDescriptor filename or file descriptor
#data: string | Uint8Array #options: WriteFileOptions #callback: NoParamCallback Return Type #
void Overload 2
#appendFile(): voidAsynchronously append data to a file, creating the file if it does not exist.
Parameters #
#file: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
#data: string | Uint8Array The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
#callback: NoParamCallback Return Type #
void function appendFileSync
Usage in Deno
import { appendFileSync } from "node:fs";
#appendFileSync(): voidSynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFileSync } from 'node:fs';
try {
appendFileSync('message.txt', 'data to append');
console.log('The "data to append" was appended to file!');
} catch (err) {
// Handle the error
}
If options is a string, then it specifies the encoding:
import { appendFileSync } from 'node:fs';
appendFileSync('message.txt', 'data to append', 'utf8');
The path may be specified as a numeric file descriptor that has been opened
for appending (using fs.open() or fs.openSync()). The file descriptor will
not be closed automatically.
import { openSync, closeSync, appendFileSync } from 'node:fs';
let fd;
try {
fd = openSync('message.txt', 'a');
appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
// Handle the error
} finally {
if (fd !== undefined)
closeSync(fd);
}
Parameters #
#path: PathOrFileDescriptor filename or file descriptor
#data: string | Uint8Array #options: WriteFileOptions Return Type #
void function chmod
Usage in Deno
import { chmod } from "node:fs";
#chmod(): voidAsynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX chmod(2) documentation for more detail.
import { chmod } from 'node:fs';
chmod('my_file.txt', 0o775, (err) => {
if (err) throw err;
console.log('The permissions for file "my_file.txt" have been changed!');
});
Parameters #
Return Type #
void function chmodSync
Usage in Deno
import { chmodSync } from "node:fs";
function chownSync
Usage in Deno
import { chownSync } from "node:fs";
function close
Usage in Deno
import { close } from "node:fs";
#close(fd: number,callback?: NoParamCallback,): voidCloses the file descriptor. No arguments other than a possible exception are given to the completion callback.
Calling fs.close() on any file descriptor (fd) that is currently in use
through any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
Parameters #
#fd: number #callback: NoParamCallback Return Type #
void function copyFile
Usage in Deno
import { copyFile } from "node:fs";
Overload 1
#copyFile(): voidAsynchronously copies src to dest. By default, dest is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
Parameters #
Return Type #
void Overload 2
function copyFileSync
Usage in Deno
import { copyFileSync } from "node:fs";
#copyFileSync(): voidSynchronously copies src to dest. By default, dest is overwritten if it
already exists. Returns undefined. Node.js makes no guarantees about the
atomicity of the copy operation. If an error occurs after the destination file
has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFileSync, constants } from 'node:fs';
// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
Parameters #
Return Type #
void function cp
Usage in Deno
import { cp } from "node:fs";
function cpSync
Usage in Deno
import { cpSync } from "node:fs";
function createReadStream
Usage in Deno
import { createReadStream } from "node:fs";
#createReadStream(path: PathLike,options?: BufferEncoding | ReadStreamOptions,): ReadStreamoptions 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 fd is specified and start is
omitted or undefined, fs.createReadStream() reads sequentially from the
current file position. The encoding can be any one of those accepted by Buffer.
If fd is specified, ReadStream will ignore the path argument and will use
the specified file descriptor. This means that no 'open' event will be
emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.
If fd points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
available. This can prevent the process from exiting and the stream from
closing naturally.
By default, the stream will emit a 'close' event after it has been
destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option,
an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is
also required.
import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
If autoClose is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If autoClose is set to true (default
behavior), on 'error' or 'end' the file descriptor will be closed
automatically.
mode sets the file mode (permission and sticky bits), but only if the
file was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });
If options is a string, then it specifies the encoding.
Parameters #
#options: BufferEncoding | ReadStreamOptions Return Type #
function createWriteStream
Usage in Deno
import { createWriteStream } from "node:fs";
#createWriteStream(path: PathLike,options?: BufferEncoding | WriteStreamOptions,): WriteStreamoptions 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 option to be set to r+ rather than the
default w. The encoding can be any one of those accepted by Buffer.
If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.
By default, the stream will emit a 'close' event after it has been
destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option it is possible to override the corresponding fs implementations for open, write, writev, and close. Overriding write() without writev() can reduce
performance as some optimizations (_writev())
will be disabled. When providing the fs option, overrides for at least one of write and writev are required. If no fd option is supplied, an override
for open is also required. If autoClose is true, an override for close is also required.
Like fs.ReadStream, if fd is specified, fs.WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be
emitted. fd should be blocking; non-blocking fds
should be passed to net.Socket.
If options is a string, then it specifies the encoding.
Parameters #
#options: BufferEncoding | WriteStreamOptions Return Type #
function existsSync
Usage in Deno
import { existsSync } from "node:fs";
#existsSync(path: PathLike): booleanReturns true if the path exists, false otherwise.
For detailed information, see the documentation of the asynchronous version of this API: exists.
fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other
Node.js callbacks. fs.existsSync() does not use a callback.
import { existsSync } from 'node:fs';
if (existsSync('/etc/passwd'))
console.log('The path exists.');
Parameters #
Return Type #
boolean function fchownSync
Usage in Deno
import { fchownSync } from "node:fs";
function fdatasync
Usage in Deno
import { fdatasync } from "node:fs";
#fdatasync(fd: number,callback: NoParamCallback,): voidForces 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. No arguments other
than a possible
exception are given to the completion callback.
Parameters #
#fd: number #callback: NoParamCallback Return Type #
void function fdatasyncSync
Usage in Deno
import { fdatasyncSync } from "node:fs";
#fdatasyncSync(fd: number): voidForces 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. Returns undefined.
Parameters #
#fd: number Return Type #
void function fstat
Usage in Deno
import { fstat } from "node:fs";
Overload 1
Overload 2
#fstat(fd: number,options: (StatOptions & { bigint?: false | undefined; }) | undefined,callback: (err: ErrnoException | null,stats: Stats,) => void,): voidOverload 3
#fstat(fd: number,options: StatOptions & { bigint: true; },callback: (err: ErrnoException | null,stats: BigIntStats,) => void,): voidParameters #
#fd: number #options: StatOptions & { bigint: true; } #callback: (err: ErrnoException | null,stats: BigIntStats,) => void Return Type #
void Overload 4
#fstat(fd: number,options: StatOptions | undefined,callback: (err: ErrnoException | null,stats: Stats | BigIntStats,) => void,): voidParameters #
#fd: number #options: StatOptions | undefined #callback: (err: ErrnoException | null,stats: Stats | BigIntStats,) => void Return Type #
void function fstatSync
Usage in Deno
import { fstatSync } from "node:fs";
Overload 1
#fstatSync(fd: number,options?: StatOptions & { bigint?: false | undefined; },): StatsOverload 2
#fstatSync(fd: number,options: StatOptions & { bigint: true; },): BigIntStatsParameters #
#fd: number #options: StatOptions & { bigint: true; } Return Type #
Overload 3
#fstatSync(fd: number,options?: StatOptions,): Stats | BigIntStatsParameters #
#fd: number #options: StatOptions Return Type #
function fsync
Usage in Deno
import { fsync } from "node:fs";
#fsync(fd: number,callback: NoParamCallback,): voidRequest 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. No arguments other
than a possible exception are given to the completion callback.
Parameters #
#fd: number #callback: NoParamCallback Return Type #
void function ftruncate
Usage in Deno
import { ftruncate } from "node:fs";
Overload 1
#ftruncate(): voidTruncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
See the POSIX ftruncate(2) documentation for more detail.
If the file referred to by the file descriptor was larger than len bytes, only
the first len bytes will be retained in the file.
For example, the following program retains only the first four bytes of the file:
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
});
If the file previously was shorter than len bytes, it is extended, and the
extended part is filled with null bytes ('\0'):
If len is negative then 0 will be used.
Parameters #
Return Type #
void Overload 2
#ftruncate(fd: number,callback: NoParamCallback,): voidAsynchronous ftruncate(2) - Truncate a file to a specified length.
Parameters #
#fd: number A file descriptor.
#callback: NoParamCallback Return Type #
void function ftruncateSync
Usage in Deno
import { ftruncateSync } from "node:fs";
function futimes
Usage in Deno
import { futimes } from "node:fs";
function glob
Usage in Deno
import { glob } from "node:fs";
Overload 1
#glob(pattern: string | string[],callback: (err: ErrnoException | null,matches: string[],) => void,): voidOverload 2
#glob(pattern: string | string[],options: GlobOptionsWithFileTypes,callback: (err: ErrnoException | null,matches: Dirent[],) => void,): voidOverload 3
#glob(pattern: string | string[],options: GlobOptionsWithoutFileTypes,callback: (err: ErrnoException | null,matches: string[],) => void,): voidOverload 4
#glob(pattern: string | string[],options: GlobOptions,callback: (err: ErrnoException | null,matches: Dirent[] | string[],) => void,): voidfunction globSync
Usage in Deno
import { globSync } from "node:fs";
Overload 1
#globSync(pattern: string | string[]): string[]Overload 2
#globSync(pattern: string | string[],options: GlobOptionsWithFileTypes,): Dirent[]Overload 3
#globSync(pattern: string | string[],options: GlobOptionsWithoutFileTypes,): string[]Parameters #
#pattern: string | string[] #options: GlobOptionsWithoutFileTypes Return Type #
string[] Overload 4
#globSync(pattern: string | string[],options: GlobOptions,): Dirent[] | string[]function lchownSync
Usage in Deno
import { lchownSync } from "node:fs";
function linkSync
Usage in Deno
import { linkSync } from "node:fs";
function lstat
Usage in Deno
import { lstat } from "node:fs";
Overload 1
#lstat(): voidRetrieves the fs.Stats for the symbolic link referred to by the path.
The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Parameters #
Return Type #
void Overload 2
#lstat(path: PathLike,options: (StatOptions & { bigint?: false | undefined; }) | undefined,callback: (err: ErrnoException | null,stats: Stats,) => void,): voidOverload 3
#lstat(path: PathLike,options: StatOptions & { bigint: true; },callback: (err: ErrnoException | null,stats: BigIntStats,) => void,): voidParameters #
#options: StatOptions & { bigint: true; } #callback: (err: ErrnoException | null,stats: BigIntStats,) => void Return Type #
void Overload 4
#lstat(path: PathLike,options: StatOptions | undefined,callback: (err: ErrnoException | null,stats: Stats | BigIntStats,) => void,): voidParameters #
#options: StatOptions | undefined #callback: (err: ErrnoException | null,stats: Stats | BigIntStats,) => void Return Type #
void function lutimes
Usage in Deno
import { lutimes } from "node:fs";
#lutimes(): voidChanges the access and modification times of a file in the same way as utimes, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.
No arguments other than a possible exception are given to the completion callback.
Parameters #
Return Type #
void function mkdir
Usage in Deno
import { mkdir } from "node:fs";
Overload 1
#mkdir(path: PathLike,options: MakeDirectoryOptions & { recursive: true; },callback: (err: ErrnoException | null,path?: string,) => void,): voidAsynchronously creates a directory.
The callback is given a possible exception and, if recursive is true, the
first directory path created, (err[, path]).path can still be undefined when recursive is true, if no directory was
created (for instance, if it was previously created).
The optional options argument can be an integer specifying mode (permission
and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that
exists results in an error only
when recursive is false. If recursive is false and the directory exists,
an EEXIST error occurs.
import { mkdir } from 'node:fs';
// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
On Windows, using fs.mkdir() on the root directory even with recursion will
result in an error:
import { mkdir } from 'node:fs';
mkdir('/', { recursive: true }, (err) => {
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
See the POSIX mkdir(2) documentation for more details.
Parameters #
#options: MakeDirectoryOptions & { recursive: true; } #callback: (err: ErrnoException | null,path?: string,) => void Return Type #
void Overload 2
#mkdir(): voidAsynchronous 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.
#callback: NoParamCallback Return Type #
void Overload 3
#mkdir(): voidAsynchronous mkdir(2) - create a directory.
Parameters #
Return Type #
void Overload 4
#mkdir(path: PathLike,callback: NoParamCallback,): voidfunction mkdirSync
Usage in Deno
import { mkdirSync } from "node:fs";
Overload 1
#mkdirSync(path: PathLike,options: MakeDirectoryOptions & { recursive: true; },): string | undefinedOverload 2
#mkdirSync(path: PathLike,options?: ,): voidSynchronous 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 #
void Overload 3
#mkdirSync(path: PathLike,options?: ,): string | undefinedSynchronous 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 #
string | undefined function mkdtemp
Usage in Deno
import { mkdtemp } from "node:fs";
Overload 1
#mkdtemp(prefix: string,options: EncodingOption,callback: (err: ErrnoException | null,folder: string,) => void,): voidCreates a unique temporary directory.
Generates six random characters to be appended behind a required prefix to create a unique temporary directory. Due to platform
inconsistencies, avoid trailing X characters in prefix. Some platforms,
notably the BSDs, can return more than six random characters, and replace
trailing X characters in prefix with random characters.
The created directory path is passed as a string to the callback's second parameter.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
The fs.mkdtemp() method will append the six randomly selected characters
directly to the prefix string. For instance, given a directory /tmp, if the
intention is to create a temporary directory within/tmp, the prefixmust end with a trailing platform-specific path separator
(import { sep } from 'node:path').
import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';
// The parent directory for the new temporary directory
const tmpDir = tmpdir();
// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmpabc123`.
// A new temporary directory is created at the file system root
// rather than *within* the /tmp directory.
});
// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmp/abc123`.
// A new temporary directory is created within
// the /tmp directory.
});
Parameters #
#prefix: string #options: EncodingOption #callback: (err: ErrnoException | null,folder: string,) => void Return Type #
void Overload 2
#mkdtemp(prefix: string,options: "buffer" | { encoding: "buffer"; },callback: (err: ErrnoException | null,folder: Buffer,) => void,): voidOverload 3
#mkdtemp(prefix: string,options: EncodingOption,callback: (err: ErrnoException | null,folder: string | Buffer,) => void,): voidAsynchronously 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: EncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
#callback: (err: ErrnoException | null,folder: string | Buffer,) => void Return Type #
void Overload 4
#mkdtemp(prefix: string,callback: (err: ErrnoException | null,folder: string,) => void,): voidfunction mkdtempSync
Usage in Deno
import { mkdtempSync } from "node:fs";
Overload 1
#mkdtempSync(prefix: string,options?: EncodingOption,): stringReturns the created directory path.
For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use.
Parameters #
#prefix: string #options: EncodingOption Return Type #
string Overload 2
#mkdtempSync(prefix: string,options: BufferEncodingOption,): BufferSynchronously 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 #
Buffer Overload 3
#mkdtempSync(prefix: string,options?: EncodingOption,): string | BufferSynchronously 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: EncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
string | Buffer function open
Usage in Deno
import { open } from "node:fs";
Overload 1
#open(path: PathLike,flags: OpenMode | undefined,mode: ,callback: (err: ErrnoException | null,fd: number,) => void,): voidAsynchronous file open. See the POSIX open(2) documentation for more details.
mode sets the file mode (permission and sticky bits), but only if the file was
created. On Windows, only the write permission can be manipulated; see chmod.
The callback gets two arguments (err, fd).
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.
Functions based on fs.open() exhibit this behavior as well:fs.writeFile(), fs.readFile(), etc.
Parameters #
Return Type #
void Overload 2
#open(path: PathLike,flags: OpenMode | undefined,callback: (err: ErrnoException | null,fd: number,) => void,): voidOverload 3
function openAsBlob
Usage in Deno
import { openAsBlob } from "node:fs";
#openAsBlob(path: PathLike,options?: OpenAsBlobOptions,): Promise<Blob>Returns a Blob whose data is backed by the given file.
The file must not be modified after the Blob is created. Any modifications
will cause reading the Blob data to fail with a DOMException error.
Synchronous stat operations on the file when the Blob is created, and before
each read in order to detect whether the file data has been modified on disk.
import { openAsBlob } from 'node:fs';
const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();
Parameters #
#options: OpenAsBlobOptions Return Type #
Promise<Blob> function opendir
Usage in Deno
import { opendir } from "node:fs";
Overload 1
#opendir(): voidAsynchronously open a directory. See the POSIX opendir(3) documentation for
more details.
Creates an fs.Dir, which contains all further functions for reading from
and cleaning up the directory.
The encoding option sets the encoding for the path while opening the
directory and subsequent read operations.
Parameters #
Return Type #
void Overload 2
function opendirSync
Usage in Deno
import { opendirSync } from "node:fs";
#opendirSync(path: PathLike,options?: OpenDirOptions,): DirSynchronously open a directory. See opendir(3).
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.
Parameters #
#options: OpenDirOptions Return Type #
function promises.access
Usage in Deno
import { promises } from "node:fs";
const { access } = 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 promises.appendFile
Usage in Deno
import { promises } from "node:fs";
const { appendFile } = 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 promises.chown
Usage in Deno
import { promises } from "node:fs";
const { chown } = promises;
function promises.copyFile
Usage in Deno
import { promises } from "node:fs";
const { copyFile } = 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 promises.cp
Usage in Deno
import { promises } from "node:fs";
const { cp } = promises;
#cp(): Promise<void>function promises.glob
Usage in Deno
import { promises } from "node:fs";
const { glob } = 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 promises.lchown
Usage in Deno
import { promises } from "node:fs";
const { lchown } = promises;
function promises.link
Usage in Deno
import { promises } from "node:fs";
const { link } = promises;
function promises.lstat
Usage in Deno
import { promises } from "node:fs";
const { lstat } = 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 promises.lutimes
Usage in Deno
import { promises } from "node:fs";
const { lutimes } = 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 promises.mkdir
Usage in Deno
import { promises } from "node:fs";
const { mkdir } = 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 promises.mkdtemp
Usage in Deno
import { promises } from "node:fs";
const { mkdtemp } = 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 promises.open
Usage in Deno
import { promises } from "node:fs";
const { open } = 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 promises.opendir
Usage in Deno
import { promises } from "node:fs";
const { opendir } = 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 promises.readdir
Usage in Deno
import { promises } from "node:fs";
const { readdir } = 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 promises.readFile
Usage in Deno
import { promises } from "node:fs";
const { readFile } = 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 promises.readlink
Usage in Deno
import { promises } from "node:fs";
const { readlink } = 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 promises.realpath
Usage in Deno
import { promises } from "node:fs";
const { realpath } = 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 promises.rename
Usage in Deno
import { promises } from "node:fs";
const { rename } = promises;
function promises.rm
Usage in Deno
import { promises } from "node:fs";
const { rm } = promises;
function promises.rmdir
Usage in Deno
import { promises } from "node:fs";
const { rmdir } = 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 promises.stat
Usage in Deno
import { promises } from "node:fs";
const { stat } = 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 promises.statfs
Usage in Deno
import { promises } from "node:fs";
const { statfs } = 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 promises.symlink
Usage in Deno
import { promises } from "node:fs";
const { symlink } = 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 promises.truncate
Usage in Deno
import { promises } from "node:fs";
const { truncate } = promises;
function promises.unlink
Usage in Deno
import { promises } from "node:fs";
const { unlink } = 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 promises.utimes
Usage in Deno
import { promises } from "node:fs";
const { utimes } = 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 promises.watch
Usage in Deno
import { promises } from "node:fs";
const { watch } = 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 promises.writeFile
Usage in Deno
import { promises } from "node:fs";
const { writeFile } = 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
#data: string
| ArrayBufferView
| Iterable<string | ArrayBufferView>
| AsyncIterable<string | ArrayBufferView>
| Stream #options: (ObjectEncodingOptions
& { mode?: Mode | undefined; flag?: OpenMode | undefined; flush?: boolean | undefined; }
& Abortable)
| BufferEncoding
| null Return Type #
Promise<void> Fulfills with undefined upon success.
function read
Usage in Deno
import { read } from "node:fs";
Overload 1
#read<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,offset: number,length: number,position: ReadPosition | null,callback: (err: ErrnoException | null,bytesRead: number,buffer: TBuffer,) => void,): voidRead data from the file specified by fd.
The callback is given the three arguments, (err, bytesRead, buffer).
If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its util.promisify() ed version, it returns
a promise for an Object with bytesRead and buffer properties.
Type Parameters #
#TBuffer extends ArrayBufferView Parameters #
#fd: number #offset: number The position in buffer to write the data to.
#length: number The number of bytes to read.
#position: ReadPosition | null Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If
position is an integer, the file position will be unchanged.
Return Type #
void Overload 2
#read<TBuffer extends ArrayBufferView>(fd: number,options: ReadAsyncOptions<TBuffer>,callback: (err: ErrnoException | null,bytesRead: number,buffer: TBuffer,) => void,): voidSimilar to the above fs.read function, this version takes an optional options object.
If not otherwise specified in an options object,
buffer defaults to Buffer.alloc(16384),
offset defaults to 0,
length defaults to buffer.byteLength, - offset as of Node 17.6.0
position defaults to null
Type Parameters #
#TBuffer extends ArrayBufferView Parameters #
Return Type #
void Overload 3
#read<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,options: ReadSyncOptions,callback: (err: ErrnoException | null,bytesRead: number,buffer: TBuffer,) => void,): voidOverload 4
#read<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,callback: (err: ErrnoException | null,bytesRead: number,buffer: TBuffer,) => void,): voidOverload 5
function readdir
Usage in Deno
import { readdir } from "node:fs";
Overload 1
#readdir(path: PathLike,options: { encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; }
| BufferEncoding
| undefined
| null,callback: (err: ErrnoException | null,files: string[],) => void,): voidReads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the filenames passed to the callback. If the encoding is set to 'buffer',
the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the files array will contain fs.Dirent objects.
Parameters #
Return Type #
void Overload 2
#readdir(path: PathLike,options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer",callback: (err: ErrnoException | null,files: Buffer[],) => void,): voidAsynchronous readdir(3) - read a directory.
Parameters #
Return Type #
void Overload 3
#readdir(path: PathLike,options: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| undefined
| null,callback: (err: ErrnoException | null,files: string[] | Buffer[],) => void,): voidAsynchronous readdir(3) - read a directory.
Parameters #
#options: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| undefined
| null The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
#callback: (err: ErrnoException | null,files: string[] | Buffer[],) => void Return Type #
void Overload 4
Overload 5
#readdir(path: PathLike,options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; },callback: (err: ErrnoException | null,files: Dirent[],) => void,): voidAsynchronous 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 #
void function readdirSync
Usage in Deno
import { readdirSync } from "node:fs";
Overload 1
#readdirSync(path: PathLike,options?: { encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; }
| BufferEncoding
| null,): string[]Reads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the filenames returned. If the encoding is set to 'buffer',
the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects.
Parameters #
Return Type #
string[] Overload 2
#readdirSync(path: PathLike,options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer",): Buffer[]Synchronous 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 #
Buffer[] Overload 3
#readdirSync(path: PathLike,options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null,): string[] | Buffer[]Synchronous 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 #
string[] | Buffer[] Overload 4
#readdirSync(path: PathLike,options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; },): Dirent[]Synchronous 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 #
Dirent[] function readFile
Usage in Deno
import { readFile } from "node:fs";
Overload 1
#readFile(): voidAsynchronously reads the entire contents of a file.
import { readFile } from 'node:fs';
readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
The callback is passed two arguments (err, data), where data is the
contents of the file.
If no encoding is specified, then the raw buffer is returned.
If options is a string, then it specifies the encoding:
import { readFile } from 'node:fs';
readFile('/etc/passwd', 'utf8', callback);
When the path is a directory, the behavior of fs.readFile() and readFileSync is platform-specific. On macOS, Linux, and Windows, an
error will be returned. On FreeBSD, a representation of the directory's contents
will be returned.
import { readFile } from 'node:fs';
// macOS, Linux, and Windows
readFile('<directory>', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
});
// FreeBSD
readFile('<directory>', (err, data) => {
// => null, <data>
});
It is possible to abort an ongoing request using an AbortSignal. If a
request is aborted the callback is called with an AbortError:
import { readFile } from 'node:fs';
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
// ...
});
// When you want to abort the request
controller.abort();
The fs.readFile() function buffers the entire file. To minimize memory costs,
when possible prefer streaming via fs.createReadStream().
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.readFile performs.
Parameters #
#path: PathOrFileDescriptor filename or file descriptor
#callback: (err: ErrnoException | null,data: Buffer,) => void Return Type #
void Overload 2
#readFile(path: PathOrFileDescriptor,options: ({ encoding: BufferEncoding; flag?: string | undefined; } & Abortable) | BufferEncoding,callback: (err: ErrnoException | null,data: string,) => void,): voidAsynchronously reads the entire contents of a file.
Parameters #
#path: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag.
If a flag is not provided, it defaults to 'r'.
#callback: (err: ErrnoException | null,data: string,) => void Return Type #
void Overload 3
#readFile(path: PathOrFileDescriptor,options: ()
| BufferEncoding
| undefined
| null,callback: (err: ErrnoException | null,data: string | Buffer,) => void,): voidAsynchronously reads the entire contents of a file.
Parameters #
#path: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
#options: ()
| BufferEncoding
| undefined
| null Either the encoding for the result, or an object that contains the encoding and an optional flag.
If a flag is not provided, it defaults to 'r'.
#callback: (err: ErrnoException | null,data: string | Buffer,) => void Return Type #
void Overload 4
#readFile(path: PathOrFileDescriptor,callback: (err: ErrnoException | null,data: Buffer,) => void,): voidAsynchronously reads the entire contents of a file.
Parameters #
#path: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
#callback: (err: ErrnoException | null,data: Buffer,) => void Return Type #
void function readFileSync
Usage in Deno
import { readFileSync } from "node:fs";
Overload 1
#readFileSync(path: PathOrFileDescriptor,options?: { encoding?: null | undefined; flag?: string | undefined; } | null,): BufferReturns the contents of the path.
For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the encoding option is specified then this function returns a
string. Otherwise it returns a buffer.
Similar to readFile, when the path is a directory, the behavior of fs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
Parameters #
#path: PathOrFileDescriptor filename or file descriptor
#options: { encoding?: null | undefined; flag?: string | undefined; } | null Return Type #
Buffer Overload 2
#readFileSync(path: PathOrFileDescriptor,options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding,): stringSynchronously reads the entire contents of a file.
Parameters #
#path: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
#options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding Either the encoding for the result, or an object that contains the encoding and an optional flag.
If a flag is not provided, it defaults to 'r'.
Return Type #
string Overload 3
#readFileSync(path: PathOrFileDescriptor,options?: ,): string | BufferSynchronously reads the entire contents of a file.
Parameters #
#path: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
#options: Either the encoding for the result, or an object that contains the encoding and an optional flag.
If a flag is not provided, it defaults to 'r'.
Return Type #
string | Buffer function readlink
Usage in Deno
import { readlink } from "node:fs";
Overload 1
#readlink(path: PathLike,options: EncodingOption,callback: (err: ErrnoException | null,linkString: string,) => void,): voidReads the contents of the symbolic link referred to by path. The callback gets
two arguments (err, linkString).
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the link path passed to the callback. If the encoding is set to 'buffer',
the link path returned will be passed as a Buffer object.
Parameters #
#options: EncodingOption #callback: (err: ErrnoException | null,linkString: string,) => void Return Type #
void Overload 2
#readlink(path: PathLike,options: BufferEncodingOption,callback: (err: ErrnoException | null,linkString: Buffer,) => void,): voidAsynchronous 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.
#callback: (err: ErrnoException | null,linkString: Buffer,) => void Return Type #
void Overload 3
#readlink(path: PathLike,options: EncodingOption,callback: (err: ErrnoException | null,linkString: string | Buffer,) => void,): voidAsynchronous readlink(2) - read value of a symbolic link.
Parameters #
#options: EncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
#callback: (err: ErrnoException | null,linkString: string | Buffer,) => void Return Type #
void Overload 4
function readlinkSync
Usage in Deno
import { readlinkSync } from "node:fs";
Overload 1
#readlinkSync(path: PathLike,options?: EncodingOption,): stringReturns the symbolic link's string value.
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the link path returned. If the encoding is set to 'buffer',
the link path returned will be passed as a Buffer object.
Parameters #
#options: EncodingOption Return Type #
string Overload 2
#readlinkSync(path: PathLike,options: BufferEncodingOption,): BufferSynchronous 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 #
Buffer Overload 3
#readlinkSync(path: PathLike,options?: EncodingOption,): string | BufferSynchronous readlink(2) - read value of a symbolic link.
Parameters #
#options: EncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
string | Buffer function readv
Usage in Deno
import { readv } from "node:fs";
Overload 1
#readv(fd: number,buffers: readonly ArrayBufferView[],cb: (err: ErrnoException | null,bytesRead: number,buffers: ArrayBufferView[],) => void,): voidRead from a file specified by fd and write to an array of ArrayBufferViews
using readv().
position is the offset from the beginning of the file from where data
should be read. If typeof position !== 'number', the data will be read
from the current position.
The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify() ed version, it returns
a promise for an Object with bytesRead and buffers properties.
Parameters #
Return Type #
void Overload 2
#readv(fd: number,buffers: readonly ArrayBufferView[],position: number | null,cb: (err: ErrnoException | null,bytesRead: number,buffers: ArrayBufferView[],) => void,): voidfunction realpath
Usage in Deno
import { realpath } from "node:fs";
Overload 1
#realpath(path: PathLike,options: EncodingOption,callback: (err: ErrnoException | null,resolvedPath: string,) => void,): voidAsynchronously computes the canonical pathname by resolving ., .., and
symbolic links.
A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.
This function behaves like realpath(3), with some exceptions:
- No case conversion is performed on case-insensitive file systems.
- The maximum number of symbolic links is platform-independent and generally
(much) higher than what the native
realpath(3)implementation supports.
The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the path passed to the callback. If the encoding is set to 'buffer',
the path returned will be passed as a Buffer object.
If path resolves to a socket or a pipe, the function will return a system
dependent name for that object.
Parameters #
#options: EncodingOption #callback: (err: ErrnoException | null,resolvedPath: string,) => void Return Type #
void Overload 2
#realpath(path: PathLike,options: BufferEncodingOption,callback: (err: ErrnoException | null,resolvedPath: Buffer,) => void,): voidAsynchronous 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.
#callback: (err: ErrnoException | null,resolvedPath: Buffer,) => void Return Type #
void Overload 3
#realpath(path: PathLike,options: EncodingOption,callback: (err: ErrnoException | null,resolvedPath: string | Buffer,) => void,): voidAsynchronous realpath(3) - return the canonicalized absolute pathname.
Parameters #
#options: EncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
#callback: (err: ErrnoException | null,resolvedPath: string | Buffer,) => void Return Type #
void Overload 4
function realpath.native
Usage in Deno
import { realpath } from "node:fs";
Overload 1
#native(path: PathLike,options: EncodingOption,callback: (err: ErrnoException | null,resolvedPath: string,) => void,): voidAsynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use for
the path passed to the callback. If the encoding is set to 'buffer',
the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on /proc in order for this function to work. Glibc does not have
this restriction.
Parameters #
#options: EncodingOption #callback: (err: ErrnoException | null,resolvedPath: string,) => void Return Type #
void Overload 2
#native(path: PathLike,options: BufferEncodingOption,callback: (err: ErrnoException | null,resolvedPath: Buffer,) => void,): voidOverload 3
#native(path: PathLike,options: EncodingOption,callback: (err: ErrnoException | null,resolvedPath: string | Buffer,) => void,): voidOverload 4
function realpathSync
Usage in Deno
import { realpathSync } from "node:fs";
Overload 1
#realpathSync(path: PathLike,options?: EncodingOption,): stringOverload 2
#realpathSync(path: PathLike,options: BufferEncodingOption,): BufferSynchronous 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 #
Buffer Overload 3
#realpathSync(path: PathLike,options?: EncodingOption,): string | BufferSynchronous realpath(3) - return the canonicalized absolute pathname.
Parameters #
#options: EncodingOption The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Return Type #
string | Buffer namespace realpathSync
Functions #
function realpathSync.native
Usage in Deno
import { realpathSync } from "node:fs";
Overload 1
#native(path: PathLike,options?: EncodingOption,): stringOverload 2
#native(path: PathLike,options: BufferEncodingOption,): BufferOverload 3
#native(path: PathLike,options?: EncodingOption,): string | Bufferfunction rename
Usage in Deno
import { rename } from "node:fs";
#rename(): voidAsynchronously rename file at oldPath to the pathname provided
as newPath. In the case that newPath already exists, it will
be overwritten. If there is a directory at newPath, an error will
be raised instead. No arguments other than a possible exception are
given to the completion callback.
See also: rename(2).
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
Parameters #
Return Type #
void function renameSync
Usage in Deno
import { renameSync } from "node:fs";
function rm
Usage in Deno
import { rm } from "node:fs";
function rmdir
Usage in Deno
import { rmdir } from "node:fs";
Overload 1
#rmdir(path: PathLike,callback: NoParamCallback,): voidAsynchronous rmdir(2). No arguments other than a possible exception are given
to the completion callback.
Using fs.rmdir() on a file (not a directory) results in an ENOENT error on
Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use rm with options { recursive: true, force: true }.
Parameters #
#callback: NoParamCallback Return Type #
void Overload 2
function rmdirSync
Usage in Deno
import { rmdirSync } from "node:fs";
#rmdirSync(path: PathLike,options?: RmDirOptions,): voidfunction stat
Usage in Deno
import { stat } from "node:fs";
Overload 1
#stat(): voidAsynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended.
Instead, user code should open/read/write the file directly and handle the
error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir
-- file.txt
- app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i < pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Parameters #
Return Type #
void Overload 2
#stat(path: PathLike,options: (StatOptions & { bigint?: false | undefined; }) | undefined,callback: (err: ErrnoException | null,stats: Stats,) => void,): voidOverload 3
#stat(path: PathLike,options: StatOptions & { bigint: true; },callback: (err: ErrnoException | null,stats: BigIntStats,) => void,): voidParameters #
#options: StatOptions & { bigint: true; } #callback: (err: ErrnoException | null,stats: BigIntStats,) => void Return Type #
void Overload 4
#stat(path: PathLike,options: StatOptions | undefined,callback: (err: ErrnoException | null,stats: Stats | BigIntStats,) => void,): voidParameters #
#options: StatOptions | undefined #callback: (err: ErrnoException | null,stats: Stats | BigIntStats,) => void Return Type #
void function statfs
Usage in Deno
import { statfs } from "node:fs";
Overload 1
#statfs(): voidOverload 2
#statfs(path: PathLike,options: (StatFsOptions & { bigint?: false | undefined; }) | undefined,callback: (err: ErrnoException | null,stats: StatsFs,) => void,): voidOverload 3
#statfs(path: PathLike,options: StatFsOptions & { bigint: true; },callback: (err: ErrnoException | null,stats: BigIntStatsFs,) => void,): voidParameters #
#options: StatFsOptions & { bigint: true; } #callback: (err: ErrnoException | null,stats: BigIntStatsFs,) => void Return Type #
void Overload 4
#statfs(path: PathLike,options: StatFsOptions | undefined,callback: (err: ErrnoException | null,stats: StatsFs | BigIntStatsFs,) => void,): voidParameters #
#options: StatFsOptions | undefined #callback: (err: ErrnoException | null,stats: StatsFs | BigIntStatsFs,) => void Return Type #
void function statfsSync
Usage in Deno
import { statfsSync } from "node:fs";
Overload 1
#statfsSync(path: PathLike,options?: StatFsOptions & { bigint?: false | undefined; },): StatsFsSynchronous statfs(2). Returns information about the mounted file system which
contains path.
In case of an error, the err.code will be one of Common System Errors.
Parameters #
#options: StatFsOptions & { bigint?: false | undefined; } Return Type #
Overload 2
#statfsSync(path: PathLike,options: StatFsOptions & { bigint: true; },): BigIntStatsFsParameters #
#options: StatFsOptions & { bigint: true; } Return Type #
Overload 3
#statfsSync(path: PathLike,options?: StatFsOptions,): StatsFs | BigIntStatsFsParameters #
#options: StatFsOptions Return Type #
function symlink
Usage in Deno
import { symlink } from "node:fs";
Overload 1
#symlink(): voidCreates the link called path pointing to target. No arguments other than a
possible exception are given to the completion callback.
See the POSIX symlink(2) documentation for more details.
The type argument is only available on Windows and ignored on other platforms.
It can be set to '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', thetarget argument will automatically be normalized to absolute path. Junction
points on NTFS volumes can only point to directories.
Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs';
symlink('./mew', './mewtwo', callback);
The above example creates a symbolic link mewtwo which points to mew in the
same directory:
$ tree .
.
├── mew
└── mewtwo -> ./mew
Parameters #
#type: = 'null' #callback: NoParamCallback Return Type #
void Overload 2
function truncate
Usage in Deno
import { truncate } from "node:fs";
Overload 1
#truncate(): voidTruncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, fs.ftruncate() is called.
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
Passing a file descriptor is deprecated and may result in an error being thrown in the future.
See the POSIX truncate(2) documentation for more details.
Parameters #
Return Type #
void Overload 2
#truncate(path: PathLike,callback: NoParamCallback,): voidfunction truncateSync
Usage in Deno
import { truncateSync } from "node:fs";
#truncateSync(path: PathLike,len?: number,): voidfunction unlink
Usage in Deno
import { unlink } from "node:fs";
#unlink(path: PathLike,callback: NoParamCallback,): voidAsynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
import { unlink } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
unlink('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was deleted');
});
fs.unlink() will not work on a directory, empty or otherwise. To remove a
directory, use rmdir.
See the POSIX unlink(2) documentation for more details.
Parameters #
#callback: NoParamCallback Return Type #
void function unwatchFile
Usage in Deno
import { unwatchFile } from "node:fs";
Overload 1
#unwatchFile(filename: PathLike,listener?: StatsListener,): voidStop watching for changes on filename. If listener is specified, only that
particular listener is removed. Otherwise, all listeners are removed,
effectively stopping watching of filename.
Calling fs.unwatchFile() with a filename that is not being watched is a
no-op, not an error.
Using watch is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.
Parameters #
#listener: StatsListener Optional, a listener previously attached using fs.watchFile()
Return Type #
void Overload 2
#unwatchFile(filename: PathLike,listener?: BigIntStatsListener,): voidfunction utimes
Usage in Deno
import { utimes } from "node:fs";
#utimes(): voidChange the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
- Values can be either numbers representing Unix epoch time in seconds,
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 #
void function utimesSync
Usage in Deno
import { utimesSync } from "node:fs";
function watch
Usage in Deno
import { watch } from "node:fs";
Overload 1
#watch(filename: PathLike,options: (WatchOptions & { encoding: "buffer"; }) | "buffer",listener?: WatchListener<Buffer>,): FSWatcherWatch for changes on filename, where filename is either a file or a
directory.
The second argument is optional. If options is provided as a string, it
specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file
which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or
disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close
the returned fs.FSWatcher.
Parameters #
#options: (WatchOptions & { encoding: "buffer"; }) | "buffer" #listener: WatchListener<Buffer> Return Type #
Overload 2
#watch(): FSWatcherWatch 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: 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.
#listener: WatchListener<string> Return Type #
Overload 3
#watch(): FSWatcherWatch 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.
#listener: WatchListener<string | Buffer> Return Type #
Overload 4
#watch(filename: PathLike,listener?: WatchListener<string>,): FSWatcherfunction watchFile
Usage in Deno
import { watchFile } from "node:fs";
Overload 1
#watchFile(filename: PathLike,options: (WatchFileOptions & { bigint?: false | undefined; }) | undefined,listener: StatsListener,): StatWatcherWatch for changes on filename. The callback listener will be called each
time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates
whether the process should continue to run as long as files are being watched.
The options object may specify an interval property indicating how often the
target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous
stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true,
the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary
to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it
will invoke the listener once, with all the fields zeroed (or, for dates, the
Unix Epoch). If the file is created later on, the listener will be called
again, with the latest stat objects. This is a change in functionality since
v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears,
then the contents of previous in the second callback event (the file's
reappearance) will be the same as the contents of previous in the first
callback event (its disappearance).
This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name
Parameters #
#options: (WatchFileOptions & { bigint?: false | undefined; }) | undefined #listener: StatsListener Return Type #
Overload 2
#watchFile(filename: PathLike,options: (WatchFileOptions & { bigint: true; }) | undefined,listener: BigIntStatsListener,): StatWatcherParameters #
#options: (WatchFileOptions & { bigint: true; }) | undefined #listener: BigIntStatsListener Return Type #
Overload 3
#watchFile(filename: PathLike,listener: StatsListener,): StatWatcherWatch for changes on filename. The callback listener will be called each time the file is accessed.
Parameters #
A path to a file or directory. If a URL is provided, it must use the file: protocol.
#listener: StatsListener Return Type #
function write
Usage in Deno
import { write } from "node:fs";
Overload 1
#write<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,offset: number
| undefined
| null,length: number
| undefined
| null,position: number
| undefined
| null,callback: (err: ErrnoException | null,written: number,buffer: TBuffer,) => void,): voidWrite buffer to the file specified by fd.
offset determines the part of the buffer to be written, and length is
an integer specifying the number of bytes to write.
position refers to the offset from the beginning of the file where this data
should be written. If typeof position !== 'number', the data will be written
at the current position. See pwrite(2).
The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.
If this method is invoked as its util.promisify() ed version, it returns
a promise for an Object with bytesWritten and buffer properties.
It is unsafe to use fs.write() multiple times on the same file without waiting
for the callback. For this scenario, createWriteStream is
recommended.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
Type Parameters #
#TBuffer extends ArrayBufferView Parameters #
Return Type #
void Overload 2
#write<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,offset: number
| undefined
| null,length: number
| undefined
| null,callback: (err: ErrnoException | null,written: number,buffer: TBuffer,) => void,): voidAsynchronously writes buffer to the file referenced by the supplied file descriptor.
Type Parameters #
#TBuffer extends ArrayBufferView Parameters #
Return Type #
void Overload 3
#write<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,offset: number
| undefined
| null,callback: (err: ErrnoException | null,written: number,buffer: TBuffer,) => void,): voidOverload 4
#write<TBuffer extends ArrayBufferView>(fd: number,buffer: TBuffer,callback: (err: ErrnoException | null,written: number,buffer: TBuffer,) => void,): voidOverload 5
#write(fd: number,string: string,position: number
| undefined
| null,encoding: BufferEncoding
| undefined
| null,callback: (err: ErrnoException | null,written: number,str: string,) => void,): voidAsynchronously writes string to the file referenced by the supplied file descriptor.
Parameters #
#fd: number A file descriptor.
#string: string A string to write.
#position: number
| undefined
| null The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
#encoding: BufferEncoding
| undefined
| null The expected string encoding.
#callback: (err: ErrnoException | null,written: number,str: string,) => void Return Type #
void Overload 6
#write(fd: number,string: string,position: number
| undefined
| null,callback: (err: ErrnoException | null,written: number,str: string,) => void,): voidAsynchronously writes string to the file referenced by the supplied file descriptor.
Parameters #
#fd: number A file descriptor.
#string: string A string to write.
#position: number
| undefined
| null The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
#callback: (err: ErrnoException | null,written: number,str: string,) => void Return Type #
void Overload 7
#write(fd: number,string: string,callback: (err: ErrnoException | null,written: number,str: string,) => void,): voidfunction writeFile
Usage in Deno
import { writeFile } from "node:fs";
Overload 1
#writeFile(file: PathOrFileDescriptor,data: string | ArrayBufferView,options: WriteFileOptions,callback: NoParamCallback,): void
Missing utf16le, latin1 and ucs2 encoding.
When file is a filename, asynchronously writes data to the file, replacing the
file if it already exists. data can be a string or a buffer.
When file is a file descriptor, the behavior is similar to calling fs.write() directly (which is recommended). See the notes below on using
a file descriptor.
The encoding option is ignored if data is a buffer.
The mode option only affects the newly created file. See open for more details.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
If options is a string, then it specifies the encoding:
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
It is unsafe to use fs.writeFile() multiple times on the same file without
waiting for the callback. For this scenario, createWriteStream is
recommended.
Similarly to fs.readFile - fs.writeFile is a convenience method that
performs multiple write calls internally to write the buffer passed to it.
For performance sensitive code consider using createWriteStream.
It is possible to use an AbortSignal to cancel an fs.writeFile().
Cancelation is "best effort", and some amount of data is likely still
to be written.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
// When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.writeFile performs.
Parameters #
#file: PathOrFileDescriptor filename or file descriptor
#data: string | ArrayBufferView #options: WriteFileOptions #callback: NoParamCallback Return Type #
void Overload 2
#writeFile(): void
Missing utf16le, latin1 and ucs2 encoding.
Asynchronously writes data to a file, replacing the file if it already exists.
Parameters #
#path: PathOrFileDescriptor A path to a file. If a URL is provided, it must use the file: protocol.
If a file descriptor is provided, the underlying file will not be closed automatically.
#data: string | ArrayBufferView The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
#callback: NoParamCallback Return Type #
void function writeFileSync
Usage in Deno
import { writeFileSync } from "node:fs";
#writeFileSync(): voidParameters #
#file: PathOrFileDescriptor filename or file descriptor
#data: string | ArrayBufferView #options: WriteFileOptions Return Type #
void function writeSync
Usage in Deno
import { writeSync } from "node:fs";
Overload 1
#writeSync(fd: number,buffer: ArrayBufferView,offset?: number | null,length?: number | null,position?: number | null,): numberOverload 2
function writev
Usage in Deno
import { writev } from "node:fs";
Overload 1
#writev(fd: number,buffers: readonly ArrayBufferView[],cb: (err: ErrnoException | null,bytesWritten: number,buffers: ArrayBufferView[],) => void,): voidWrite an array of ArrayBufferViews to the file specified by fd using writev().
position is the offset from the beginning of the file where this data
should be written. If typeof position !== 'number', the data will be written
at the current position.
The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without
waiting for the callback. For this scenario, use createWriteStream.
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.
Parameters #
Return Type #
void Overload 2
#writev(fd: number,buffers: readonly ArrayBufferView[],position: number | null,cb: (err: ErrnoException | null,bytesWritten: number,buffers: ArrayBufferView[],) => void,): voidfunction writevSync
Usage in Deno
import { writevSync } from "node:fs";
#writevSync(fd: number,buffers: readonly ArrayBufferView[],position?: number,): numberfunction exists
Usage in Deno
import { exists } from "node:fs";
#exists(path: PathLike,callback: (exists: boolean) => void,): voidTest whether or not the given path exists by checking with the file system.
Then call the callback argument with either true or false:
import { exists } from 'node:fs';
exists('/etc/passwd', (e) => {
console.log(e ? 'it exists' : 'no passwd!');
});
The parameters for this callback are not consistent with other Node.js
callbacks. Normally, the first parameter to a Node.js callback is an err parameter, optionally followed by other parameters. The fs.exists() callback
has only one boolean parameter. This is one reason fs.access() is recommended
instead of fs.exists().
Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile() is not recommended. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file does not exist.
write (NOT RECOMMENDED)
import { exists, open, close } from 'node:fs';
exists('myfile', (e) => {
if (e) {
console.error('myfile already exists');
} else {
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
}
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { open, close, exists } from 'node:fs';
exists('myfile', (e) => {
if (e) {
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
} else {
console.error('myfile does not exist');
}
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process.
Parameters #
Return Type #
void function lchmod
Usage in Deno
import { lchmod } from "node:fs";
function lchmodSync
Usage in Deno
import { lchmodSync } from "node:fs";
function promises.lchmod
Usage in Deno
import { promises } from "node:fs";
const { lchmod } = promises;
#lchmod(): Promise<void>interface _GlobOptions
Usage in Deno
import { type _GlobOptions } from "node:fs";
Type Parameters #
Properties #
#withFileTypes: boolean | undefined true if the glob should return paths as Dirents, false otherwise.
interface BigIntOptions
Usage in Deno
import { type BigIntOptions } from "node:fs";
interface BigIntStatsFs
Usage in Deno
import { type BigIntStatsFs } from "node:fs";
interface CopyOptions
Usage in Deno
import { type CopyOptions } from "node:fs";
interface CopyOptionsBase
Usage in Deno
import { type CopyOptionsBase } from "node:fs";
Properties #
#dereference: boolean Dereference symlinks
#errorOnExist: boolean When force is false, and the destination
exists, throw an error.
Overwrite existing file or directory. _The copy
operation will ignore errors if you set this to false and the destination
exists. Use the errorOnExist option to change this behavior.
#preserveTimestamps: boolean When true timestamps from src will
be preserved.
#verbatimSymlinks: boolean When true, path resolution for symlinks will be skipped
interface CopySyncOptions
Usage in Deno
import { type CopySyncOptions } from "node:fs";
interface CreateReadStreamFSImplementation
Usage in Deno
import { type CreateReadStreamFSImplementation } from "node:fs";
interface CreateWriteStreamFSImplementation
Usage in Deno
import { type CreateWriteStreamFSImplementation } from "node:fs";
interface FSWatcher
Usage in Deno
import { type FSWatcher } from "node:fs";
Methods #
Stop watching for changes on the given fs.FSWatcher. Once stopped, the fs.FSWatcher object is no longer usable.
When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active. Calling watcher.ref() multiple times will have
no effect.
By default, all fs.FSWatcher objects are "ref'ed", making it normally
unnecessary to call watcher.ref() unless watcher.unref() had been
called previously.
When called, the active fs.FSWatcher object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
event loop running, the process may exit before the fs.FSWatcher object's
callback is invoked. Calling watcher.unref() multiple times will have
no effect.
#addListener(event: string,listener: (...args: any[]) => void,): this events.EventEmitter
- change
- close
- error
#addListener(event: "change",listener: (eventType: string,filename: string | Buffer,) => void,): this #addListener(event: "close",listener: () => void,): this #addListener(event: "error",listener: (error: Error) => void,): this #prependListener(event: string,listener: (...args: any[]) => void,): this #prependListener(event: "change",listener: (eventType: string,filename: string | Buffer,) => void,): this #prependListener(event: "close",listener: () => void,): this #prependListener(event: "error",listener: (error: Error) => void,): this #prependOnceListener(event: string,listener: (...args: any[]) => void,): this #prependOnceListener(event: "change",listener: (eventType: string,filename: string | Buffer,) => void,): this #prependOnceListener(event: "close",listener: () => void,): this #prependOnceListener(event: "error",listener: (error: Error) => void,): this interface GlobOptions
Usage in Deno
import { type GlobOptions } from "node:fs";
interface GlobOptionsWithFileTypes
Usage in Deno
import { type GlobOptionsWithFileTypes } from "node:fs";
Properties #
#withFileTypes: true interface GlobOptionsWithoutFileTypes
Usage in Deno
import { type GlobOptionsWithoutFileTypes } from "node:fs";
Properties #
#withFileTypes: false | undefined interface MakeDirectoryOptions
Usage in Deno
import { type MakeDirectoryOptions } from "node:fs";
Properties #
interface ObjectEncodingOptions
Usage in Deno
import { type ObjectEncodingOptions } from "node:fs";
interface OpenAsBlobOptions
Usage in Deno
import { type OpenAsBlobOptions } from "node:fs";
interface OpenDirOptions
Usage in Deno
import { type OpenDirOptions } from "node:fs";
interface promises.CreateReadStreamOptions
Usage in Deno
import { type promises } from "node:fs";
type { CreateReadStreamOptions } = promises;
interface promises.CreateWriteStreamOptions
Usage in Deno
import { type promises } from "node:fs";
type { CreateWriteStreamOptions } = promises;
interface promises.FileChangeInfo
Usage in Deno
import { type promises } from "node:fs";
type { FileChangeInfo } = promises;
interface promises.FileHandle
Usage in Deno
import { type promises } from "node:fs";
type { FileHandle } = 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 promises.FileReadOptions
Usage in Deno
import { type promises } from "node:fs";
type { FileReadOptions } = promises;
interface promises.ReadableWebStreamOptions
Usage in Deno
import { type promises } from "node:fs";
type { ReadableWebStreamOptions } = promises;
interface ReadAsyncOptions
Usage in Deno
import { type ReadAsyncOptions } from "node:fs";
interface ReadStreamOptions
Usage in Deno
import { type ReadStreamOptions } from "node:fs";
interface ReadSyncOptions
Usage in Deno
import { type ReadSyncOptions } from "node:fs";
interface RmDirOptions
Usage in Deno
import { type RmDirOptions } from "node:fs";
Properties #
#maxRetries: number | undefined If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or
EPERM error is encountered, Node.js will retry the operation with a linear
backoff wait of retryDelay ms longer on each try. This option represents the
number of retries. This option is ignored if the recursive option is not
true.
#retryDelay: number | undefined The amount of time in milliseconds to wait between retries.
This option is ignored if the recursive option is not true.
interface RmOptions
Usage in Deno
import { type RmOptions } from "node:fs";
Properties #
#maxRetries: number | undefined If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or
EPERM error is encountered, Node.js will retry the operation with a linear
backoff wait of retryDelay ms longer on each try. This option represents the
number of retries. This option is ignored if the recursive option is not
true.
If true, perform a recursive directory removal. In
recursive mode, operations are retried on failure.
#retryDelay: number | undefined The amount of time in milliseconds to wait between retries.
This option is ignored if the recursive option is not true.
interface StatFsOptions
Usage in Deno
import { type StatFsOptions } from "node:fs";
interface StatOptions
Usage in Deno
import { type StatOptions } from "node:fs";
class Stats
Usage in Deno
import { Stats } from "node:fs";
A fs.Stats object provides information about a file.
Objects returned from stat, lstat, fstat, and
their synchronous counterparts are of this type.
If bigint in the options passed to those methods is true, the numeric values
will be bigint instead of number, and the object will contain additional
nanosecond-precision properties suffixed with Ns. Stat objects are not to be created directly using the new keyword.
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
bigint version:
BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
Constructors #
#Stats() interface StatsBase
Usage in Deno
import { type StatsBase } from "node:fs";
Type Parameters #
#T Properties #
Methods #
#isDirectory(): boolean #isBlockDevice(): boolean #isCharacterDevice(): boolean #isSymbolicLink(): boolean class StatsFs
Usage in Deno
import { StatsFs } from "node:fs";
Provides information about a mounted file system.
Objects returned from statfs and its synchronous counterpart are of
this type. If bigint in the options passed to those methods is true, the
numeric values will be bigint instead of number.
StatFs {
type: 1397114950,
bsize: 4096,
blocks: 121938943,
bfree: 61058895,
bavail: 61058895,
files: 999,
ffree: 1000000
}
bigint version:
StatFs {
type: 1397114950n,
bsize: 4096n,
blocks: 121938943n,
bfree: 61058895n,
bavail: 61058895n,
files: 999n,
ffree: 1000000n
}
interface StatsFsBase
Usage in Deno
import { type StatsFsBase } from "node:fs";
interface StatSyncFn
Usage in Deno
import { type StatSyncFn } from "node:fs";
Call Signatures #
(path: PathLike,options?: StatSyncOptions & { bigint?: false | undefined; throwIfNoEntry: false; },): Stats | undefined (path: PathLike,options: StatSyncOptions & { bigint: true; throwIfNoEntry: false; },): BigIntStats | undefined (path: PathLike,options?: StatSyncOptions & { bigint?: false | undefined; },): Stats (path: PathLike,options: StatSyncOptions & { bigint: true; },): BigIntStats (path: PathLike,options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false | undefined; },): Stats | BigIntStats (path: PathLike,options?: StatSyncOptions,): interface StatSyncOptions
Usage in Deno
import { type StatSyncOptions } from "node:fs";
Properties #
#throwIfNoEntry: boolean | undefined interface StatWatcher
Usage in Deno
import { type StatWatcher } from "node:fs";
Class: fs.StatWatcher
Methods #
When called, requests that the Node.js event loop not exit so long as the fs.StatWatcher is active. Calling watcher.ref() multiple times will have
no effect.
By default, all fs.StatWatcher objects are "ref'ed", making it normally
unnecessary to call watcher.ref() unless watcher.unref() had been
called previously.
When called, the active fs.StatWatcher object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
event loop running, the process may exit before the fs.StatWatcher object's
callback is invoked. Calling watcher.unref() multiple times will have
no effect.
interface StreamOptions
Usage in Deno
import { type StreamOptions } from "node:fs";
Properties #
#highWaterMark: number | undefined interface WatchFileOptions
Usage in Deno
import { type WatchFileOptions } from "node:fs";
Watch for changes on filename. The callback listener will be called each
time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates
whether the process should continue to run as long as files are being watched.
The options object may specify an interval property indicating how often the
target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous
stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true,
the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary
to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it
will invoke the listener once, with all the fields zeroed (or, for dates, the
Unix Epoch). If the file is created later on, the listener will be called
again, with the latest stat objects. This is a change in functionality since
v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears,
then the contents of previous in the second callback event (the file's
reappearance) will be the same as the contents of previous in the first
callback event (its disappearance).
This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name
Properties #
interface WriteStreamOptions
Usage in Deno
import { type WriteStreamOptions } from "node:fs";
interface WriteVResult
Usage in Deno
import { type WriteVResult } from "node:fs";
Properties #
#bytesWritten: number namespace constants
Usage in Deno
import { constants } from "node:fs";
Variables #
Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.
namespace promises
Usage in Deno
import { promises } from "node:fs";
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.
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 src to dest. By default, dest is overwritten if it
already exists.
Asynchronously copies the entire directory structure from src to dest,
including subdirectories and files.
Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail.
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.
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.
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.
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 #
type alias BigIntStatsListener
Usage in Deno
import { type BigIntStatsListener } from "node:fs";
Definition #
(curr: BigIntStats,prev: BigIntStats,) => void type alias BufferEncodingOption
Usage in Deno
import { type BufferEncodingOption } from "node:fs";
Definition #
"buffer" | { encoding: "buffer"; } type alias CustomEvents
Usage in Deno
import { type CustomEvents } from "node:fs";
string & {} allows to allow any kind of strings for the event but still allows to have auto completion for the normal events.
Definition #
[Key in string & { } | symbol]: (...args: any[]) => void type alias NoParamCallback
Usage in Deno
import { type NoParamCallback } from "node:fs";
Definition #
(err: ErrnoException | null) => void type alias PathOrFileDescriptor
Usage in Deno
import { type PathOrFileDescriptor } from "node:fs";
type alias ReadPosition
Usage in Deno
import { type ReadPosition } from "node:fs";
Definition #
number | bigint type alias ReadStreamEvents
Usage in Deno
import { type ReadStreamEvents } from "node:fs";
The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted.
Definition #
{ close: () => void; data: (chunk: Buffer | string) => void; end: () => void; error: (err: Error) => void; open: (fd: number) => void; pause: () => void; readable: () => void; ready: () => void; resume: () => void; } & CustomEvents type alias StatsListener
Usage in Deno
import { type StatsListener } from "node:fs";
type alias symlink.Type
Usage in Deno
import { symlink } from "node:fs";
Definition #
"dir"
| "file"
| "junction" type alias WatchEventType
Usage in Deno
import { type WatchEventType } from "node:fs";
Definition #
"rename" | "change" type alias WatchListener
Usage in Deno
import { type WatchListener } from "node:fs";
Type Parameters #
#T Definition #
(event: WatchEventType,filename: T | null,) => void type alias WriteFileOptions
Usage in Deno
import { type WriteFileOptions } from "node:fs";
Definition #
(ObjectEncodingOptions
& Abortable
& { mode?: Mode | undefined; flag?: string | undefined; flush?: boolean | undefined; })
| BufferEncoding
| null type alias WriteStreamEvents
Usage in Deno
import { type WriteStreamEvents } from "node:fs";
The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted.
Definition #
{ close: () => void; drain: () => void; error: (err: Error) => void; finish: () => void; open: (fd: number) => void; pipe: (src: stream.Readable) => void; ready: () => void; unpipe: (src: stream.Readable) => void; } & CustomEvents variable constants.COPYFILE_EXCL
Usage in Deno
import { constants } from "node:fs";
Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
Type #
number variable constants.COPYFILE_FICLONE
Usage in Deno
import { constants } from "node:fs";
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
Type #
number variable constants.COPYFILE_FICLONE_FORCE
Usage in Deno
import { constants } from "node:fs";
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.
Type #
number variable constants.F_OK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.access(). File is visible to the calling process.
Type #
number variable constants.O_APPEND
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
Type #
number variable constants.O_CREAT
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
Type #
number variable constants.O_DIRECT
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
Type #
number variable constants.O_DIRECTORY
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
Type #
number variable constants.O_DSYNC
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
Type #
number variable constants.O_EXCL
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
Type #
number variable constants.O_NOATIME
Usage in Deno
import { constants } from "node:fs";
constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
Type #
number variable constants.O_NOCTTY
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
Type #
number variable constants.O_NOFOLLOW
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
Type #
number variable constants.O_NONBLOCK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
Type #
number variable constants.O_RDONLY
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating to open a file for read-only access.
Type #
number variable constants.O_RDWR
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating to open a file for read-write access.
Type #
number variable constants.O_SYMLINK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
Type #
number variable constants.O_SYNC
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
Type #
number variable constants.O_TRUNC
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
Type #
number variable constants.O_WRONLY
Usage in Deno
import { constants } from "node:fs";
Constant for fs.open(). Flag indicating to open a file for write-only access.
Type #
number variable constants.R_OK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.access(). File can be read by the calling process.
Type #
number variable constants.S_IFBLK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
Type #
number variable constants.S_IFCHR
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
Type #
number variable constants.S_IFDIR
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
Type #
number variable constants.S_IFIFO
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
Type #
number variable constants.S_IFLNK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
Type #
number variable constants.S_IFMT
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
Type #
number variable constants.S_IFREG
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
Type #
number variable constants.S_IFSOCK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
Type #
number variable constants.S_IRGRP
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
Type #
number variable constants.S_IROTH
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
Type #
number variable constants.S_IRUSR
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
Type #
number variable constants.S_IRWXG
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
Type #
number variable constants.S_IRWXO
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
Type #
number variable constants.S_IRWXU
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
Type #
number variable constants.S_IWGRP
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
Type #
number variable constants.S_IWOTH
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
Type #
number variable constants.S_IWUSR
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
Type #
number variable constants.S_IXGRP
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
Type #
number variable constants.S_IXOTH
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
Type #
number variable constants.S_IXUSR
Usage in Deno
import { constants } from "node:fs";
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
Type #
number variable constants.UV_FS_O_FILEMAP
Usage in Deno
import { constants } from "node:fs";
When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.
Type #
number variable constants.W_OK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.access(). File can be written by the calling process.
Type #
number variable constants.X_OK
Usage in Deno
import { constants } from "node:fs";
Constant for fs.access(). File can be executed by the calling process.
Type #
number variable promises.constants
Usage in Deno
import { promises } from "node:fs";
const { constants } = promises;
Type #
fsConstants