Node.js File System Module

Strengthen your Node.js expertise with this comprehensive flashcard set dedicated to the File System (fs) module. Designed for developers, technical interview preparation, certification study, and day-to-day backend development, this collection covers both fundamental concepts and advanced file system operations used in real-world Node.js applications. Topics include: • File and directory manipulation • Callback, Promise-based, and synchronous APIs • File descriptors and FileHandle objects • Reading and writing files efficiently • Streams (ReadStream and WriteStream) • Directory handling with fs.Dir and fs.Dirent • File watching with fs.watch() and fs.watchFile() • File system statistics and metadata • File permissions, ownership, and modes • Path handling using strings, Buffers, and file URLs • FS constants and flags • Performance considerations and thread pool behavior • Cross-platform caveats and operating system differences • Error handling and asynchronous execution patterns • Production best practices for scalable Node.js applications Whether you're preparing for a Node.js interview, building backend services, working with file uploads, implementing storage systems, or improving your understanding of operating system interactions, these flashcards help you learn faster and retain critical knowledge. The set progresses from core concepts to advanced APIs, making it suitable for intermediate, senior, and lead-level JavaScript developers. Each card focuses on practical understanding, common pitfalls, performance trade-offs, and real-world usage scenarios encountered in modern Node.js development. You may also be interested in: Master Node.js: From Basics to Production Node.js Stream Module Node.js Cluster Module Node.js Child Process Module Node.js Buffer API Interview Questions Node.js Crypto Module Node.js Operating System Module

Knowledge check

Take a test before studying to see which topics you know and where the gaps are.

Take the test

Messenger lessons

Study cards and revisit what you have learned in interactive lessons.

How lessons work

Spaced repetition

Get individual cards to review at intervals that help you remember them longer.

How repetition works
File system

The node:fs module enables interacting with the file system in away modeled on standard POSIX functions.

1/268
Promise example
Promise-based operations return a promise that is fulfilled when theasynchronous operation is complete.

The Promise form is available from node:fs/promises or fs.promises. Use await or then()/catch() to receive the result or handle a rejection. Unlike a synchronous call, awaiting an I/O promise does not block the event loop while the file operation is pending.

2/268
Callback example

The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception.

3/268
Synchronous example
The synchronous APIs block the Node.js event loop and further JavaScriptexecution until the operation is complete. Exceptions are thrown immediatelyand can be handled using try…catch, or can be allowed to bubble up.
4/268
Promises API
The fs/promises API provides asynchronous file system methods that returnpromises.
5/268
Class: FileHandle
A <FileHandle> object is an object wrapper for a numeric file descriptor. Instances of the <FileHandle> object are created by the fsPromises.open()method. All <FileHandle> objects are <EventEmitter>s.
6/268
Event: 'close'
The 'close' event is emitted when the <FileHandle> has been closed and can nolonger be used.

The FileHandle emits close after the underlying descriptor has been closed. Any later operation on that handle is invalid. Use the event to observe lifecycle completion, but await filehandle.close() when your code needs deterministic cleanup.

7/268
filehandle.appendFile()

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().

8/268
filehandle.chmod(mode)

Modifies the permissions on the file.

9/268
filehandle.chown(uid, gid)

Changes the ownership of the file.

10/268
filehandle.close()

Closes the file handle after waiting for any pending operation on the handle to complete.


Returns: <Promise> Fulfills with undefined upon success.

close() waits for operations already in progress on this FileHandle and returns a Promise that fulfills when closing finishes. Afterward the handle must not be used. Close handles in finally or with asynchronous disposal so an error does not leave a descriptor open.

11/268
filehandle .createReadStream([options])

options <Object>encoding <string> Default: null


autoClose <boolean> Default: true


emitClose <boolean> Default: true

12/268
filehandle .createWriteStream([options])

options <Object>encoding <string> Default: 'utf8'


autoClose <boolean> Default: true


emitClose <boolean> Default: true

13/268
filehandle.datasync()

Forces all currently queued I/O operations associated with the file to theoperating system's synchronized I/O completion state. Refer to the POSIXfdatasync(2) documentation for details.

14/268
filehandle.fd
<number> The numeric file descriptor managed by the <FileHandle> object.

This number is the operating-system descriptor associated with the open FileHandle. It identifies the open file, not a path or its contents. Closing the FileHandle invalidates the descriptor, so do not cache it for later I/O.

15/268
filehandle.read(buffer, offset, length, position)

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.

16/268
filehandle.read([options])

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.

17/268
filehandle.read(buffer[, options])
buffer <Buffer> | <TypedArray> | <DataView> A buffer that will be filled with thefile data read. 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 thenumber of bytes read is zero.
18/268
filehandle .readableWebStream([options])

An error will be thrown if this method is called more than once or is calledafter the FileHandle is closed or closing.

19/268
filehandle.readFile(options)
options <Object> | <string>encoding <string> | <null> Default: nullsignal <AbortSignal> allows aborting an in-progress readFile Asynchronously reads the entire contents of a file. If options is a string, then it specifies the encoding.
20/268
filehandle.readLines([options])
options <Object>encoding <string> Default: nullautoClose <boolean> Default: trueemitClose <boolean> Default: truestart <integer>end <integer> Default: InfinityhighWaterMark <integer> Default: 64 * 1024 Returns: <readline.InterfaceConstructor>
21/268
filehandle.readv(buffers[, position])
buffers <Buffer[]> | <TypedArray[]> | <DataView[]> position <integer> | <null> The offset from the beginning of the file wherethe data should be read from. If position is not a number, the data willbe read from the current position. Default: null
22/268
filehandle.stat([options])
options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. Returns: <Promise> Fulfills with an <fs.Stats> for the file.

stat() returns a Promise for an fs.Stats object describing the open file. The bigint option can request bigint values for numeric fields. This inspects the target already opened by the FileHandle; use a path-based fsPromises.stat() when no handle is open.

23/268
filehandle.sync()
Returns: <Promise> Fulfills with undefined upon success. Request that all data for the open file descriptor is flushed to the storagedevice. The specific implementation is operating system and device specific.Refer to the POSIX fsync(2) documentation for more detail.
24/268
filehandle.truncate(len)
len <integer> Default: 0 Returns: <Promise> Fulfills with undefined upon success. Truncates the file. If the file was larger than len bytes, only the first len bytes will beretained in the file. The following example retains only the first four bytes of the file:
25/268
filehandle.utimes(atime, mtime)
atime <number> | <string> | <Date> mtime <number> | <string> | <Date> Returns: <Promise> Change the file system timestamps of the object referenced by the <FileHandle>then fulfills the promise with no arguments upon success.
26/268
filehandle.write(buffer, offset[, length[, position]])
buffer <Buffer> | <TypedArray> | <DataView> offset <integer> The start position from within buffer where the datato write begins. length <integer> The number of bytes from buffer to write. Default:buffer.byteLength - offset Returns: <Promise>
27/268
filehandle.write(buffer[, options])
buffer <Buffer> | <TypedArray> | <DataView> options <Object>offset <integer> Default: 0length <integer> Default: buffer.byteLength - offsetposition <integer> Default: null Returns: <Promise> Write buffer to the file.
28/268
filehandle.write(string[, position[, encoding]])
string <string> position <integer> | <null> The offset from the beginning of the file where thedata from string should be written. If position is not a number thedata will be written at the current position. See the POSIX pwrite(2)documentation for more detail. Default: null
29/268
filehandle.writeFile(data, options)
data <string> | <Buffer> | <TypedArray> | <DataView> | <AsyncIterable> | <Iterable> | <Stream> options <Object> | <string>encoding <string> | <null> The expected character encoding when data is astring. Default: 'utf8'
30/268
filehandle.writev(buffers[, position])
buffers <Buffer[]> | <TypedArray[]> | <DataView[]> position <integer> | <null> The offset from the beginning of the file where thedata from buffers should be written. If position is not a number,the data will be written at the current position. Default: null
31/268
filehandle[Symbol .asyncDispose]()
An alias for filehandle.close().

This asynchronous disposal method is an alias for filehandle.close(). It lets an await using declaration close the FileHandle as its scope ends. The close is awaited so pending work can finish before the resource is released.

32/268
fsPromises.access(path[, mode])
path <string> | <Buffer> | <URL> mode <integer> Default: fs.constants.F_OK Returns: <Promise> Fulfills with undefined upon success.
33/268
fsPromises.appendFile(path, data[, options])
path <string> | <Buffer> | <URL> | <FileHandle> filename or <FileHandle> data <string> | <Buffer> Returns: <Promise> Fulfills with undefined upon success. If options is a string, then it specifies the encoding.
34/268
fsPromises.chmod(path, mode)
path <string> | <Buffer> | <URL> mode <string> | <integer> Returns: <Promise> Fulfills with undefined upon success. Changes the permissions of a file.

mode is a permission bit mask, commonly expressed with octal syntax. The Promise fulfills with undefined when the change succeeds and rejects on permission or path errors. This changes permission bits; chown() changes owner and group.

35/268
fsPromises.chown(path, uid, gid)
path <string> | <Buffer> | <URL> uid <integer> gid <integer> Returns: <Promise> Fulfills with undefined upon success. Changes the ownership of a file.

uid and gid identify the new owner and group for the path. The Promise fulfills with undefined on success and rejects if the operation fails, including insufficient permission. This changes ownership rather than file permission bits; chmod() handles modes.

36/268
fsPromises.copyFile(src, dest[, mode])
src <string> | <Buffer> | <URL> source filename to copy dest <string> | <Buffer> | <URL> destination filename of the copy operation Returns: <Promise> Fulfills with undefined upon success.
37/268
fsPromises.cp(src, dest[, options])
src <string> | <URL> source path to copy. dest <string> | <URL> destination path to copy to. Returns: <Promise> Fulfills with undefined upon success. Asynchronously copies the entire directory structure from src to dest,including subdirectories and files.
38/268
fsPromises.glob(pattern[, options])
pattern <string> | <string[]> Returns: <AsyncIterator> An AsyncIterator that yields the paths of filesthat match the pattern.
39/268
fsPromises.lchmod(path, mode)
Deprecated since: v10.0.0 path <string> | <Buffer> | <URL> mode <integer> Returns: <Promise> Fulfills with undefined upon success. Changes the permissions on a symbolic link. This method is only implemented on macOS.
40/268
fsPromises.lchown(path, uid, gid)
path <string> | <Buffer> | <URL> uid <integer> gid <integer> Returns: <Promise> Fulfills with undefined upon success. Changes the ownership on a symbolic link.

lchown() changes ownership of a symbolic link itself where the platform supports it, rather than following the link to its target. uid and gid are numeric identifiers. The Promise rejects on failure; compare chown() when the target file is intended.

41/268
fsPromises.lutimes(path, atime, mtime)
path <string> | <Buffer> | <URL> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> Returns: <Promise> Fulfills with undefined upon success.
42/268
fsPromises.link(existingPath, newPath)
existingPath <string> | <Buffer> | <URL> newPath <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with undefined upon success. Creates a new link from the existingPath to the newPath. See the POSIXlink(2) documentation for more detail.
43/268
fsPromises.lstat(path[, options])
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. Returns: <Promise> Fulfills with the <fs.Stats> object for the givensymbolic link path.
44/268
fsPromises.mkdir(path[, options])
path <string> | <Buffer> | <URL> options <Object> | <integer>recursive <boolean> Default: falsemode <string> | <integer> Not supported on Windows. Default: 0o777. Asynchronously creates a directory.
45/268
fsPromises.mkdtemp(prefix[, options])
prefix <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <Promise> Fulfills with a string containing the file system pathof the newly created temporary directory.
46/268
fsPromises.open(path, flags[, mode])
path <string> | <Buffer> | <URL> flags <string> | <number> See support of file system flags.Default: 'r'. mode <string> | <integer> Sets the file mode (permission and sticky bits)if the file is created. Default: 0o666 (readable and writable)
47/268
fsPromises.opendir(path[, options])
path <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with an <fs.Dir>. Asynchronously open a directory for iterative scanning. See the POSIXopendir(3) documentation for more detail. Example using async iteration:
48/268
fsPromises.readdir(path[, options])
path <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with an array of the names of the files inthe directory excluding '.' and '..'. Reads the contents of a directory. If options.withFileTypes is set to true, the returned array will contain<fs.Dirent> objects.
49/268
fsPromises.readFile(path[, options])
path <string> | <Buffer> | <URL> | <FileHandle> filename or FileHandle Returns: <Promise> Fulfills with the contents of the file. Asynchronously reads the entire contents of a file. If options is a string, then it specifies the encoding.
50/268
fsPromises.readlink(path[, options])
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <Promise> Fulfills with the linkString upon success.
51/268
fsPromises.realpath(path[, options])
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <Promise> Fulfills with the resolved path upon success. Only paths that can be converted to UTF8 strings are supported.
52/268
fsPromises.rename(oldPath, newPath)
oldPath <string> | <Buffer> | <URL> newPath <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with undefined upon success. Renames oldPath to newPath.

oldPath names the existing entry and newPath names its destination. The Promise fulfills with undefined on success. A rename may replace an existing destination depending on platform rules; handle errors and do not assume cross-device moves work.

53/268
fsPromises.rmdir(path[, options])
path <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with undefined upon success. Removes the directory identified by path. To get a behavior similar to the rm -rf Unix command, usefsPromises.rm() with options { recursive: true, force: true }.
54/268
fsPromises.rm(path[, options])
path <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with undefined upon success. Removes files and directories (modeled on the standard POSIX rm utility).
55/268
fsPromises.stat(path[, options])
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. Returns: <Promise> Fulfills with the <fs.Stats> object for thegiven path.
56/268
fsPromises.statfs(path[, options])
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.StatFs> object should be bigint. Default: false. Returns: <Promise> Fulfills with the <fs.StatFs> object for thegiven path.
57/268
fsPromises.symlink(target, path[, type])
target <string> | <Buffer> | <URL> path <string> | <Buffer> | <URL> type <string> | <null> Default: null Returns: <Promise> Fulfills with undefined upon success. Creates a symbolic link.
58/268
fsPromises.truncate(path[, len])
path <string> | <Buffer> | <URL> len <integer> Default: 0 Returns: <Promise> Fulfills with undefined upon success. Truncates (shortens or extends the length) of the content at path to lenbytes.

len is a byte length and defaults to zero. If the file is longer, it is shortened; if shorter, it can be extended with zero-filled bytes. The Promise fulfills with undefined on success. This operation changes file size, not its path or permissions.

59/268
fsPromises.unlink(path)
path <string> | <Buffer> | <URL> Returns: <Promise> Fulfills with undefined upon success.
60/268
fsPromises.utimes(path, atime, mtime)
path <string> | <Buffer> | <URL> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> Returns: <Promise> Fulfills with undefined upon success. Change the file system timestamps of the object referenced by path.
61/268
fsPromises.watch(filename[, options])
filename <string> | <Buffer> | <URL> Returns: <AsyncIterator> of objects with the properties:eventType <string> The type of changefilename <string> | <Buffer> | <null> The name of the file changed.
62/268
fsPromises.writeFile(file, data[, options])
file <string> | <Buffer> | <URL> | <FileHandle> filename or FileHandle data <string> | <Buffer> | <TypedArray> | <DataView> | <AsyncIterable> | <Iterable> | <Stream> Returns: <Promise> Fulfills with undefined upon success.
63/268
fsPromises.constants
<Object> Returns an object containing commonly used constants for file systemoperations. The object is the same as fs.constants. See FS constantsfor more details.

These named values are the same as fs.constants and include file access and open flags. Pass the appropriate documented flag to access() or open(). A constant names an operating-system option; it does not perform file I/O by itself.

64/268
Callback API
The callback APIs perform all operations asynchronously, without blocking theevent loop, then invoke a callback function upon completion or error.
65/268
fs.access(path[, mode], callback)
path <string> | <Buffer> | <URL> mode <integer> Default: fs.constants.F_OK callback <Function>err <Error>
66/268
fs.appendFile(path, data[, options], callback)
path <string> | <Buffer> | <URL> | <number> filename or file descriptor data <string> | <Buffer> callback <Function>err <Error> Asynchronously append data to a file, creating the file if it does not yetexist. data can be a string or a <Buffer>.
67/268
fs.chmod(path, mode, callback)
path <string> | <Buffer> | <URL> mode <string> | <integer> callback <Function>err <Error> Asynchronously changes the permissions of a file. No arguments other than apossible exception are given to the completion callback.
68/268
File modes
The mode argument used in both the fs.chmod() and fs.chmodSync()methods is a numeric bitmask created using a logical OR of the followingconstants: Constant Octal Description
69/268
fs.chown(path, uid, gid, callback)
path <string> | <Buffer> | <URL> uid <integer> gid <integer> callback <Function>err <Error> Asynchronously changes owner and group of a file. No arguments other than apossible exception are given to the completion callback.
70/268
fs.close(fd[, callback])
fd <integer> callback <Function>err <Error> Closes the file descriptor. No arguments other than a possible exception aregiven to the completion callback. See the POSIX close(2) documentation for more detail.
71/268
fs.copyFile(src, dest[, mode], callback)
src <string> | <Buffer> | <URL> source filename to copy dest <string> | <Buffer> | <URL> destination filename of the copy operation mode <integer> modifiers for copy operation. Default: 0. callback <Function>err <Error>
72/268
fs.cp(src, dest[, options], callback)
src <string> | <URL> source path to copy. dest <string> | <URL> destination path to copy to. callback <Function>err <Error> Asynchronously copies the entire directory structure from src to dest,including subdirectories and files.
73/268
fs.createReadStream(path[, options])
path <string> | <Buffer> | <URL> Returns: <fs.ReadStream> By default, the stream will emit a 'close' event after it has beendestroyed. Set the emitClose option to false to change this behavior.
74/268
fs.createWriteStream(path[, options])
path <string> | <Buffer> | <URL> Returns: <fs.WriteStream> By default, the stream will emit a 'close' event after it has beendestroyed. Set the emitClose option to false to change this behavior. If options is a string, then it specifies the encoding.
75/268
fs.exists(path, callback)
path <string> | <Buffer> | <URL> callback <Function>exists <boolean> Test whether or not the element at the given path exists by checking with the file system.Then call the callback argument with either true or false:
76/268
fs.fchmod(fd, mode, callback)
fd <integer> mode <string> | <integer> callback <Function>err <Error> Sets the permissions on the file. No arguments other than a possible exceptionare given to the completion callback. See the POSIX fchmod(2) documentation for more detail.
77/268
fs.fchown(fd, uid, gid, callback)
fd <integer> uid <integer> gid <integer> callback <Function>err <Error> Sets the owner of the file. No arguments other than a possible exception aregiven to the completion callback. See the POSIX fchown(2) documentation for more detail.
78/268
fs.fdatasync(fd, callback)
fd <integer> callback <Function>err <Error>
79/268
fs.fstat(fd[, options], callback)
fd <integer> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. callback <Function>err <Error>stats <fs.Stats> Invokes the callback with the <fs.Stats> for the file descriptor.
80/268
fs.fsync(fd, callback)
fd <integer> callback <Function>err <Error>
81/268
fs.ftruncate(fd[, len], callback)
fd <integer> len <integer> Default: 0 callback <Function>err <Error> Truncates the file descriptor. No arguments other than a possible exception aregiven to the completion callback. See the POSIX ftruncate(2) documentation for more detail.
82/268
fs.futimes(fd, atime, mtime, callback)
fd <integer> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> callback <Function>err <Error> Change the file system timestamps of the object referenced by the supplied filedescriptor. See fs.utimes().
83/268
fs.glob(pattern[, options], callback)
pattern <string> | <string[]> callback <Function>err <Error> Retrieves the files matching the specified pattern.
84/268
fs.lchmod(path, mode, callback)
path <string> | <Buffer> | <URL> mode <integer> callback <Function>err <Error> | <AggregateError> Changes the permissions on a symbolic link. No arguments other than a possibleexception are given to the completion callback.
85/268
fs.lchown(path, uid, gid, callback)
path <string> | <Buffer> | <URL> uid <integer> gid <integer> callback <Function>err <Error> Set the owner of the symbolic link. No arguments other than a possibleexception are given to the completion callback.
86/268
fs.lutimes(path, atime, mtime, callback)
path <string> | <Buffer> | <URL> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> callback <Function>err <Error> No arguments other than a possible exception are given to the completioncallback.
87/268
fs.link(existingPath, newPath, callback)
existingPath <string> | <Buffer> | <URL> newPath <string> | <Buffer> | <URL> callback <Function>err <Error>
88/268
fs.lstat(path[, options], callback)
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. callback <Function>err <Error>stats <fs.Stats>
89/268
fs.mkdir(path[, options], callback)
path <string> | <Buffer> | <URL> options <Object> | <integer>recursive <boolean> Default: falsemode <string> | <integer> Not supported on Windows. Default: 0o777. Asynchronously creates a directory.
90/268
fs.mkdtemp(prefix[, options], callback)
prefix <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' callback <Function>err <Error>directory <string> Creates a unique temporary directory.
91/268
fs.open(path[, flags[, mode]], callback)
path <string> | <Buffer> | <URL> flags <string> | <number> See support of file system flags.Default: 'r'. mode <string> | <integer> Default: 0o666 (readable and writable) callback <Function>err <Error>fd <integer>
92/268
fs.openAsBlob(path[, options])
path <string> | <Buffer> | <URL> options <Object>type <string> An optional mime type for the blob. Returns: <Promise> Fulfills with a <Blob> upon success. Returns a <Blob> whose data is backed by the given file.
93/268
fs.opendir(path[, options], callback)
path <string> | <Buffer> | <URL> callback <Function>err <Error>dir <fs.Dir> Asynchronously open a directory. See the POSIX opendir(3) documentation formore details.
94/268
fs.read(fd, buffer, offset, length, position, callback)
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> The buffer that the data will bewritten to. offset <integer> The position in buffer to write the data to. length <integer> The number of bytes to read. Read data from the file specified by fd. For example:
95/268
fs.read(fd[, options], callback)
fd <integer> options <Object>buffer <Buffer> | <TypedArray> | <DataView> Default: Buffer.alloc(16384)offset <integer> Default: 0length <integer> Default: buffer.byteLength - offsetposition <integer> | <bigint> | <null> Default: null
96/268
fs.read(fd, buffer[, options], callback)
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> The buffer that the data will bewritten to. options <Object>offset <integer> Default: 0length <integer> Default: buffer.byteLength - offsetposition <integer> | <bigint> Default: null
97/268
fs.readdir(path[, options], callback)
path <string> | <Buffer> | <URL> callback <Function>err <Error>files <string[]> | <Buffer[]> | <fs.Dirent[]> See the POSIX readdir(3) documentation for more details.
98/268
fs.readFile(path[, options], callback)
path <string> | <Buffer> | <URL> | <integer> filename or file descriptor callback <Function>err <Error> | <AggregateError>data <string> | <Buffer> Asynchronously reads the entire contents of a file.
99/268
File descriptors
Any specified file descriptor has to support reading. If a file descriptor is specified as the path, it will not be closedautomatically.
100/268
Performance Considerations
The fs.readFile() method asynchronously reads the contents of a file intomemory one chunk at a time, allowing the event loop to turn between each chunk.This allows the read operation to have less impact on other activity that maybe using the underlying libuv thread pool but means that it will take longerto read a complete file into memory.
101/268
fs.readlink(path[, options], callback)
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' callback <Function>err <Error>linkString <string> | <Buffer> See the POSIX readlink(2) documentation for more details.
102/268
fs.readv(fd, buffers[, position], callback)
fd <integer> buffers <ArrayBufferView[]> position <integer> | <null> Default: null callback <Function>err <Error>bytesRead <integer>buffers <ArrayBufferView[]> Read from a file specified by fd and write to an array of ArrayBufferViewsusing readv().
103/268
fs.realpath(path[, options], callback)
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' callback <Function>err <Error>resolvedPath <string> | <Buffer> This function behaves like realpath(3), with some exceptions:
104/268
fs.realpath.native(path[, options], callback)
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' callback <Function>err <Error>resolvedPath <string> | <Buffer> Asynchronous realpath(3). The callback gets two arguments (err, resolvedPath).
105/268
fs.rename(oldPath, newPath, callback)
oldPath <string> | <Buffer> | <URL> newPath <string> | <Buffer> | <URL> callback <Function>err <Error> See also: rename(2).
106/268
fs.rmdir(path[, options], callback)
path <string> | <Buffer> | <URL> callback <Function>err <Error> Asynchronous rmdir(2). No arguments other than a possible exception are givento the completion callback.
107/268
fs.rm(path[, options], callback)
path <string> | <Buffer> | <URL> callback <Function>err <Error> Asynchronously removes files and directories (modeled on the standard POSIX rmutility). No arguments other than a possible exception are given to thecompletion callback.
108/268
fs.stat(path[, options], callback)
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. callback <Function>err <Error>stats <fs.Stats>
109/268
fs.statfs(path[, options], callback)
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.StatFs> object should be bigint. Default: false. callback <Function>err <Error>stats <fs.StatFs>
110/268
fs.symlink(target, path[, type], callback)
target <string> | <Buffer> | <URL> path <string> | <Buffer> | <URL> type <string> | <null> Default: null callback <Function>err <Error> See the POSIX symlink(2) documentation for more details.
111/268
fs.truncate(path[, len], callback)
path <string> | <Buffer> | <URL> len <integer> Default: 0 callback <Function>err <Error> | <AggregateError>
112/268
fs.unlink(path, callback)
path <string> | <Buffer> | <URL> callback <Function>err <Error> Asynchronously removes a file or symbolic link. No arguments other than apossible exception are given to the completion callback.
113/268
fs.unwatchFile(filename[, listener])
filename <string> | <Buffer> | <URL> listener <Function> Optional, a listener previously attached usingfs.watchFile() Calling fs.unwatchFile() with a filename that is not being watched is ano-op, not an error.
114/268
fs.utimes(path, atime, mtime, callback)
path <string> | <Buffer> | <URL> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> callback <Function>err <Error> Change the file system timestamps of the object referenced by path.
115/268
fs.watch(filename[, options][, listener])
filename <string> | <Buffer> | <URL> listener <Function> | <undefined> Default: undefinedeventType <string>filename <string> | <Buffer> | <null> Returns: <fs.FSWatcher>
116/268
Caveats
The fs.watch API is not 100% consistent across platforms, and isunavailable in some situations. On Windows, no events will be emitted if the watched directory is moved orrenamed. An EPERM error is reported when the watched directory is deleted. Availability # On Linux systems, this uses inotify(7).
117/268
fs.watchFile(filename[, options], listener)
filename <string> | <Buffer> | <URL> options <Object>bigint <boolean> Default: falsepersistent <boolean> Default: trueinterval <integer> Default: 5007 listener <Function>current <fs.Stats>previous <fs.Stats> Returns: <fs.StatWatcher>
118/268
fs.write(fd, buffer, offset[, length[, position]], callback)
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> offset <integer> Default: 0 length <integer> Default: buffer.byteLength - offset position <integer> | <null> Default: null Write buffer to the file specified by fd.
119/268
fs.write(fd, buffer[, options], callback)
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> options <Object>offset <integer> Default: 0length <integer> Default: buffer.byteLength - offsetposition <integer> Default: null Write buffer to the file specified by fd.
120/268
fs.write(fd, string[, position[, encoding]], callback)
fd <integer> string <string> position <integer> | <null> Default: null encoding <string> Default: 'utf8' callback <Function>err <Error>written <integer>string <string> encoding is the expected string encoding.
121/268
fs.writeFile(file, data[, options], callback)
file <string> | <Buffer> | <URL> | <integer> filename or file descriptor data <string> | <Buffer> | <TypedArray> | <DataView> callback <Function>err <Error> | <AggregateError> The encoding option is ignored if data is a buffer.
122/268
Using fs.writeFile() with file descriptors
When file is a file descriptor, the behavior is almost identical to directlycalling fs.write() like:
123/268
fs.writev(fd, buffers[, position], callback)
fd <integer> buffers <ArrayBufferView[]> position <integer> | <null> Default: null callback <Function>err <Error>bytesWritten <integer>buffers <ArrayBufferView[]> Write an array of ArrayBufferViews to the file specified by fd usingwritev().
124/268
Synchronous API
The synchronous APIs perform all operations synchronously, blocking theevent loop until the operation completes or fails.

Synchronous methods such as readFileSync() finish before returning and throw errors directly. They block the Node.js event loop while I/O is pending, so prefer Promise or callback forms for server request paths. They can be convenient during startup or small command-line tasks.

125/268
fs.accessSync(path[, mode])
path <string> | <Buffer> | <URL> mode <integer> Default: fs.constants.F_OK If any of the accessibility checks fail, an Error will be thrown. Otherwise,the method will return undefined.
126/268
fs.appendFileSync(path, data[, options])
path <string> | <Buffer> | <URL> | <number> filename or file descriptor data <string> | <Buffer> Synchronously append data to a file, creating the file if it does not yetexist. data can be a string or a <Buffer>.
127/268
fs.chmodSync(path, mode)
path <string> | <Buffer> | <URL> mode <string> | <integer> For detailed information, see the documentation of the asynchronous version ofthis API: fs.chmod(). See the POSIX chmod(2) documentation for more detail.
128/268
fs.chownSync(path, uid, gid)
path <string> | <Buffer> | <URL> uid <integer> gid <integer> Synchronously changes owner and group of a file. Returns undefined.This is the synchronous version of fs.chown(). See the POSIX chown(2) documentation for more detail.
129/268
fs.closeSync(fd)
fd <integer> Closes the file descriptor. Returns undefined. Calling fs.closeSync() on any file descriptor (fd) that is currently in usethrough any other fs operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail.
130/268
fs.copyFileSync(src, dest[, mode])
src <string> | <Buffer> | <URL> source filename to copy dest <string> | <Buffer> | <URL> destination filename of the copy operation mode <integer> modifiers for copy operation. Default: 0.
131/268
fs.cpSync(src, dest[, options])
src <string> | <URL> source path to copy. dest <string> | <URL> destination path to copy to. Synchronously copies the entire directory structure from src to dest,including subdirectories and files.
132/268
fs.existsSync(path)
path <string> | <Buffer> | <URL> Returns: <boolean> Returns true if the path exists, false otherwise. For detailed information, see the documentation of the asynchronous version ofthis API: fs.exists().
133/268
fs.fchmodSync(fd, mode)
fd <integer> mode <string> | <integer> Sets the permissions on the file. Returns undefined. See the POSIX fchmod(2) documentation for more detail.

This synchronous method changes permission bits for the file identified by an open numeric descriptor. mode is a bit mask, typically written in octal. It throws on failure and blocks until the operation completes; chmodSync() targets a path instead.

134/268
fs.fchownSync(fd, uid, gid)
fd <integer> uid <integer> The file's new owner's user id. gid <integer> The file's new group's group id. Sets the owner of the file. Returns undefined. See the POSIX fchown(2) documentation for more detail.
135/268
fs.fdatasyncSync(fd)
fd <integer> Forces all currently queued I/O operations associated with the file to theoperating system's synchronized I/O completion state. Refer to the POSIXfdatasync(2) documentation for details. Returns undefined.
136/268
fs.fstatSync(fd[, options])
fd <integer> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.Stats> object should be bigint. Default: false. Returns: <fs.Stats> Retrieves the <fs.Stats> for the file descriptor. See the POSIX fstat(2) documentation for more detail.
137/268
fs.fsyncSync(fd)
fd <integer> Request that all data for the open file descriptor is flushed to the storagedevice. The specific implementation is operating system and device specific.Refer to the POSIX fsync(2) documentation for more detail. Returns undefined.
138/268
fs.ftruncateSync(fd[, len])
fd <integer> len <integer> Default: 0 Truncates the file descriptor. Returns undefined. For detailed information, see the documentation of the asynchronous version ofthis API: fs.ftruncate().

len is the new byte length and defaults to zero. This synchronous operation changes the size of the open file identified by fd and throws on error. Use truncateSync() for a path, or the asynchronous ftruncate() in code that must avoid blocking.

139/268
fs.futimesSync(fd, atime, mtime)
fd <integer> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> Synchronous version of fs.futimes(). Returns undefined.

This synchronous call sets access time and modification time on the file identified by fd. atime and mtime are the new timestamp values. It throws on failure; utimesSync() accepts a path rather than an open descriptor.

140/268
fs.globSync(pattern[, options])
pattern <string> | <string[]> Returns: <string[]> paths of files that match the pattern.
141/268
fs.lchmodSync(path, mode)
Deprecated since: v0.4.7 path <string> | <Buffer> | <URL> mode <integer> Changes the permissions on a symbolic link. Returns undefined. This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail.
142/268
fs.lchownSync(path, uid, gid)
path <string> | <Buffer> | <URL> uid <integer> The file's new owner's user id. gid <integer> The file's new group's group id. Set the owner for the path. Returns undefined. See the POSIX lchown(2) documentation for more details.
143/268
fs.lutimesSync(path, atime, mtime)
path <string> | <Buffer> | <URL> atime <number> | <string> | <Date> mtime <number> | <string> | <Date>
144/268
fs.linkSync(existingPath, newPath)
existingPath <string> | <Buffer> | <URL> newPath <string> | <Buffer> | <URL> Creates a new link from the existingPath to the newPath. See the POSIXlink(2) documentation for more detail. Returns undefined.

This creates a hard link named newPath to the existing filesystem entry. Both names refer to the same underlying file data while the link exists. The synchronous call blocks and throws on error; a hard link is different from a symbolic link.

145/268
fs.lstatSync(path[, options])
path <string> | <Buffer> | <URL> Returns: <fs.Stats> Retrieves the <fs.Stats> for the symbolic link referred to by path. See the POSIX lstat(2) documentation for more details.
146/268
fs.mkdirSync(path[, options])
path <string> | <Buffer> | <URL> options <Object> | <integer>recursive <boolean> Default: falsemode <string> | <integer> Not supported on Windows. Default: 0o777. Returns: <string> | <undefined>
147/268
fs.mkdtempSync(prefix[, options])
prefix <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <string> Returns the created directory path. For detailed information, see the documentation of the asynchronous version ofthis API: fs.mkdtemp().
148/268
fs.opendirSync(path[, options])
path <string> | <Buffer> | <URL> Returns: <fs.Dir> Synchronously open a directory. See opendir(3). Creates an <fs.Dir>, which contains all further functions for reading fromand cleaning up the directory.
149/268
fs.openSync(path[, flags[, mode]])
path <string> | <Buffer> | <URL> flags <string> | <number> Default: 'r'.See support of file system flags. mode <string> | <integer> Default: 0o666 Returns: <number> Returns an integer representing the file descriptor.
150/268
fs.readdirSync(path[, options])
path <string> | <Buffer> | <URL> Returns: <string[]> | <Buffer[]> | <fs.Dirent[]> Reads the contents of the directory. See the POSIX readdir(3) documentation for more details.
151/268
fs.readFileSync(path[, options])
path <string> | <Buffer> | <URL> | <integer> filename or file descriptor options <Object> | <string>encoding <string> | <null> Default: nullflag <string> See support of file system flags. Default: 'r'. Returns: <string> | <Buffer>
152/268
fs.readlinkSync(path[, options])
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <string> | <Buffer> Returns the symbolic link's string value. See the POSIX readlink(2) documentation for more details.
153/268
fs.readSync(fd, buffer, offset, length[, position])
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> offset <integer> length <integer> position <integer> | <bigint> | <null> Default: null Returns: <number> Returns the number of bytesRead.
154/268
fs.readSync(fd, buffer[, options])
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> options <Object>offset <integer> Default: 0length <integer> Default: buffer.byteLength - offsetposition <integer> | <bigint> | <null> Default: null Returns: <number>
155/268
fs.readvSync(fd, buffers[, position])
fd <integer> buffers <ArrayBufferView[]> position <integer> | <null> Default: null Returns: <number> The number of bytes read. For detailed information, see the documentation of the asynchronous version ofthis API: fs.readv().
156/268
fs.realpathSync(path[, options])
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <string> | <Buffer> Returns the resolved pathname.
157/268
fs.realpathSync.native(path[, options])
path <string> | <Buffer> | <URL> options <string> | <Object>encoding <string> Default: 'utf8' Returns: <string> | <Buffer> Synchronous realpath(3). Only paths that can be converted to UTF8 strings are supported.
158/268
fs.renameSync(oldPath, newPath)
oldPath <string> | <Buffer> | <URL> newPath <string> | <Buffer> | <URL> Renames the file from oldPath to newPath. Returns undefined. See the POSIX rename(2) documentation for more details.

oldPath is the source name and newPath is the destination. The call returns only after the rename attempt completes and throws on error. Renaming across file systems can fail, so handle exceptions rather than assuming it is a general-purpose move.

159/268
fs.rmdirSync(path[, options])
path <string> | <Buffer> | <URL> Synchronous rmdir(2). Returns undefined. Using fs.rmdirSync() on a file (not a directory) results in an ENOENT erroron Windows and an ENOTDIR error on POSIX.
160/268
fs.rmSync(path[, options])
path <string> | <Buffer> | <URL> Synchronously removes files and directories (modeled on the standard POSIX rmutility). Returns undefined.
161/268
fs.statSync(path[, options])
path <string> | <Buffer> | <URL> Returns: <fs.Stats> Retrieves the <fs.Stats> for the path.
162/268
fs.statfsSync(path[, options])
path <string> | <Buffer> | <URL> options <Object>bigint <boolean> Whether the numeric values in the returned<fs.StatFs> object should be bigint. Default: false. Returns: <fs.StatFs> In case of an error, the err.code will be one of Common System Errors.
163/268
fs.symlinkSync(target, path[, type])
target <string> | <Buffer> | <URL> path <string> | <Buffer> | <URL> type <string> | <null> Default: null Returns undefined. For detailed information, see the documentation of the asynchronous version ofthis API: fs.symlink().

target is the path stored inside the new symbolic link, and path is the name of the link to create. The link and its target are distinct entries. The synchronous method blocks and throws on failure; linkSync() creates a hard link instead.

164/268
fs.truncateSync(path[, len])
path <string> | <Buffer> | <URL> len <integer> Default: 0 Truncates the file. Returns undefined. A file descriptor can also bepassed as the first argument. In this case, fs.ftruncateSync() is called.
165/268
fs.unlinkSync(path)
path <string> | <Buffer> | <URL> Synchronous unlink(2). Returns undefined.

unlinkSync() removes a directory entry for a file or symbolic link. It does not recursively remove a directory; use rmSync() or rmdirSync() as appropriate. The synchronous call blocks and throws if removal fails.

166/268
fs.utimesSync(path, atime, mtime)
path <string> | <Buffer> | <URL> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> Returns undefined. For detailed information, see the documentation of the asynchronous version ofthis API: fs.utimes().

atime sets the last-access time and mtime the last-modification time for the path. The synchronous method blocks and throws on failure. Use futimesSync() when operating through an open descriptor instead of a path.

167/268
fs.writeFileSync(file, data[, options])
file <string> | <Buffer> | <URL> | <integer> filename or file descriptor data <string> | <Buffer> | <TypedArray> | <DataView> Returns undefined. The mode option only affects the newly created file. See fs.open()for more details.
168/268
fs.writeSync(fd, buffer, offset[, length[, position]])
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> offset <integer> Default: 0 length <integer> Default: buffer.byteLength - offset position <integer> | <null> Default: null Returns: <number> The number of bytes written.
169/268
fs.writeSync(fd, buffer[, options])
fd <integer> buffer <Buffer> | <TypedArray> | <DataView> options <Object>offset <integer> Default: 0length <integer> Default: buffer.byteLength - offsetposition <integer> Default: null Returns: <number> The number of bytes written.
170/268
fs.writeSync(fd, string[, position[, encoding]])
fd <integer> string <string> position <integer> | <null> Default: null encoding <string> Default: 'utf8' Returns: <number> The number of bytes written. For detailed information, see the documentation of the asynchronous version ofthis API: fs.write(fd, string...).
171/268
fs.writevSync(fd, buffers[, position])
fd <integer> buffers <ArrayBufferView[]> position <integer> | <null> Default: null Returns: <number> The number of bytes written. For detailed information, see the documentation of the asynchronous version ofthis API: fs.writev().
172/268
Common Objects
The common objects are shared by all of the file system API variants(promise, callback, and synchronous).

Common fs objects include Dir for directory iteration, Dirent for entry types, Stats for file metadata, and stream or watcher objects. Their methods expose different information: a Dirent describes an entry type, while Stats includes sizes and timestamps.

173/268
Class: fs.Dir
A class representing a directory stream. Created by fs.opendir(), fs.opendirSync(), orfsPromises.opendir().
174/268
dir.close()
Returns: <Promise> 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 beenclosed.

dir.close() returns a Promise that fulfills once the directory handle is closed. A closed Dir cannot be read again. Use a finally block when an error or early exit could skip normal cleanup; closeSync() is the blocking variant.

175/268
dir.close(callback)
callback <Function>err <Error> Asynchronously close the directory's underlying resource handle.Subsequent reads will result in errors. The callback will be called after the resource handle has been closed.
176/268
dir.closeSync()
Synchronously close the directory's underlying resource handle.Subsequent reads will result in errors.

The synchronous close releases a Dir handle immediately and blocks until complete. After closing, further reads are invalid. Use dir.close() for the Promise form, and close the handle when directory iteration ends early.

177/268
dir.path
<string> The read-only path of this directory as was provided to fs.opendir(),fs.opendirSync(), or fsPromises.opendir().

This property identifies the path of the directory represented by the Dir object. It does not list entries or read file contents. Use dir.read() or async iteration to obtain directory entries and close the Dir when finished.

178/268
dir.read()
Returns: <Promise> Fulfills with a <fs.Dirent> | <null> 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 nullif there are no more directory entries to read.
179/268
dir.read(callback)
callback <Function>err <Error>dirent <fs.Dirent> | <null> Asynchronously read the next directory entry via readdir(3) as an<fs.Dirent>.
180/268
dir.readSync()
Returns: <fs.Dirent> | <null> Synchronously read the next directory entry as an <fs.Dirent>. See thePOSIX readdir(3) documentation for more detail. If there are no more directory entries to read, null will be returned.
181/268
dir[Symbol.asyncIterator]()
Returns: <AsyncIterator> An AsyncIterator of <fs.Dirent> Asynchronously iterates over the directory until all entries havebeen read. Refer to the POSIX readdir(3) documentation for more detail. See <fs.Dir> for an example.
182/268
Class: fs.Dirent
A representation of a directory entry, which can be a file or a subdirectorywithin the directory, as returned by reading from an <fs.Dir>. Thedirectory entry is a combination of the file name and file type pairs.
183/268
dirent.isBlockDevice()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a block device.

isBlockDevice() returns a boolean indicating whether this directory entry is a block device. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

184/268
dirent.isCharacterDevice()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a character device.

isCharacterDevice() returns a boolean indicating whether this directory entry is a character device. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

185/268
dirent.isDirectory()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a file systemdirectory.

isDirectory() returns a boolean indicating whether this directory entry is a directory. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

186/268
dirent.isFIFO()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a first-in-first-out(FIFO) pipe.

isFIFO() returns a boolean indicating whether this directory entry is a FIFO or named pipe. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

187/268
dirent.isFile()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a regular file.

isFile() returns a boolean indicating whether this directory entry is a regular file. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

188/268
dirent.isSocket()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a socket.

isSocket() returns a boolean indicating whether this directory entry is a socket. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

189/268
dirent.isSymbolicLink()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a symbolic link.

isSymbolicLink() returns a boolean indicating whether this directory entry is a symbolic link. Dirent values can be obtained while reading a directory with withFileTypes: true. This type check does not read the entry contents; use a full path and stat/lstat when detailed metadata is needed.

190/268
dirent.name
<string> | <Buffer> The file name that this <fs.Dirent> object refers to. The type of thisvalue is determined by the options.encoding passed to fs.readdir() orfs.readdirSync().

name is the entry name returned during directory reading, without the parent directory path. Combine it with parentPath when a full path is needed. For the entry type, call a method such as isFile() or isDirectory().

191/268
dirent.parentPath
<string> The path to the parent directory of the file this <fs.Dirent> object refers to.

parentPath identifies the directory containing this Dirent. Combine it with dirent.name to locate the entry when needed. It is a path property, not a test for the entry type or file contents.

192/268
dirent.path
<string> Alias for dirent.parentPath.

This legacy path property identifies the containing directory of a Dirent. Newer Node.js versions expose parentPath; check the runtime version when using either name. It is not the full path of the entry without its name.

193/268
Class: fs.FSWatcher
Extends <EventEmitter> A successful call to fs.watch() method will return a new <fs.FSWatcher>object. All <fs.FSWatcher> objects emit a 'change' event whenever a specific watchedfile is modified.
194/268
Event: 'change'
eventType <string> The type of change event that has occurred filename <string> | <Buffer> The filename that changed (if relevant/available) Emitted when something changes in a watched directory or file.See more details in fs.watch().
195/268
Event: 'close'
Emitted when the watcher stops watching for changes. The closed<fs.FSWatcher> object is no longer usable in the event handler.

This close event means the FSWatcher stopped watching and its underlying resource was released. It can follow watcher.close() or an underlying failure. It does not mean that the watched file was deleted; listen for change and error separately.

196/268
Event: 'error'
error <Error> Emitted when an error occurs while watching the file. The errored<fs.FSWatcher> object is no longer usable in the event handler.

An FSWatcher emits error if watching fails. Register an error listener to avoid an unhandled event and decide whether to restart or stop watching. Watching behavior varies by operating system; this event is not the same as a normal change notification.

197/268
watcher.close()
Stop watching for changes on the given <fs.FSWatcher>. Once stopped, the<fs.FSWatcher> object is no longer usable.

close() stops an FSWatcher from observing further file changes. Use it when the watcher is no longer needed, especially for long-lived services. Closing a watcher releases its resources; it does not delete or modify the watched file.

198/268
watcher.ref()
Returns: <fs.FSWatcher> 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 haveno effect.
199/268
watcher.unref()
Returns: <fs.FSWatcher>
200/268
Class: fs.StatWatcher
Extends <EventEmitter> A successful call to fs.watchFile() method will return a new <fs.StatWatcher>object.

StatWatcher is created by fs.watchFile(), which polls metadata rather than receiving fs.watch() events. Its ref() and unref() methods affect whether the watcher keeps the event loop alive. Use fs.unwatchFile() to stop it.

201/268
watcher.ref()
Returns: <fs.StatWatcher> 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 haveno effect.
202/268
watcher.unref()
Returns: <fs.StatWatcher>
203/268
Class: fs.ReadStream
Extends: <stream.Readable> Instances of <fs.ReadStream> are created and returned using thefs.createReadStream() function.

fs.ReadStream is a readable stream for file data, often created by fs.createReadStream(). It emits data as chunks rather than loading the entire file at once. Handle errors and close or destroy the stream when it is no longer needed.

204/268
Event: 'close'
Emitted when the <fs.ReadStream>'s underlying file descriptor has been closed.

The ReadStream emits close after its underlying resource is closed. It can occur after normal completion or destruction; end is the event that indicates no more readable data. Handle error separately to distinguish a failed read from successful completion.

205/268
Event: 'open'
fd <integer> Integer file descriptor used by the <fs.ReadStream>. Emitted when the <fs.ReadStream>'s file descriptor has been opened.

The ReadStream emits open when its file descriptor has been opened. The event carries the descriptor number. It indicates the file was opened, not that all data has been read; data and end events describe reading progress.

206/268
Event: 'ready'
Emitted when the <fs.ReadStream> is ready to be used. Fires immediately after 'open'.

The ReadStream emits ready when it is prepared for use, immediately after open. A stream can still fail during later reads, so register an error listener. The event does not mean the entire file has been loaded.

207/268
readStream.bytesRead
<number> The number of bytes that have been read so far.

bytesRead counts the number of bytes emitted by this ReadStream so far. It can help monitor progress, but it is not necessarily the total file size. The value grows as data is read; a completed stream may have read only a selected range.

208/268
readStream.path
<string> | <Buffer>
209/268
readStream.pending
<boolean> This property is true if the underlying file has not been opened yet,i.e. before the 'ready' event is emitted.

pending is true while the ReadStream waits for its underlying file to be opened. Once the open step finishes, the stream can begin reading or report an error. It does not mean that application data is still waiting in a queue.

210/268
Class: fs.Stats
A <fs.Stats> object provides information about a file.
211/268
stats.isBlockDevice()
Returns: <boolean> Returns true if the <fs.Stats> object describes a block device.

isBlockDevice() returns true when the fs.Stats object describes a block device. The object is a snapshot returned by stat(), lstat() or fstat(). Use lstat() when the symbolic link itself must be inspected rather than following its target.

212/268
stats.isCharacterDevice()
Returns: <boolean> Returns true if the <fs.Stats> object describes a character device.

isCharacterDevice() returns true when the fs.Stats object describes a character device. The object is a snapshot returned by stat(), lstat() or fstat(). Use lstat() when the symbolic link itself must be inspected rather than following its target.

213/268
stats.isDirectory()
Returns: <boolean> Returns true if the <fs.Stats> object describes a file system directory.
214/268
stats.isFIFO()
Returns: <boolean> Returns true if the <fs.Stats> object describes a first-in-first-out (FIFO)pipe.

isFIFO() returns true when the fs.Stats object describes a FIFO or named pipe. The object is a snapshot returned by stat(), lstat() or fstat(). Use lstat() when the symbolic link itself must be inspected rather than following its target.

215/268
stats.isFile()
Returns: <boolean> Returns true if the <fs.Stats> object describes a regular file.

isFile() returns true when the fs.Stats object describes a regular file. The object is a snapshot returned by stat(), lstat() or fstat(). Use lstat() when the symbolic link itself must be inspected rather than following its target.

216/268
stats.isSocket()
Returns: <boolean> Returns true if the <fs.Stats> object describes a socket.

isSocket() returns true when the fs.Stats object describes a socket. The object is a snapshot returned by stat(), lstat() or fstat(). Use lstat() when the symbolic link itself must be inspected rather than following its target.

217/268
stats.isSymbolicLink()
Returns: <boolean> Returns true if the <fs.Stats> object describes a symbolic link. This method is only valid when using fs.lstat().

isSymbolicLink() returns true when the fs.Stats object describes a symbolic link. The object is a snapshot returned by stat(), lstat() or fstat(). Use lstat() when the symbolic link itself must be inspected rather than following its target.

218/268
stats.dev
<number> | <bigint> The numeric identifier of the device containing the file.

stats.dev reports the identifier of the device containing the file from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

219/268
stats.ino
<number> | <bigint> The file system specific "Inode" number for the file.

stats.ino reports the filesystem inode number identifying the entry on that device from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

220/268
stats.mode
<number> | <bigint> A bit-field describing the file type and mode.

stats.mode reports the file type and permission bit mask from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

221/268
stats.nlink
<number> | <bigint> The number of hard-links that exist for the file.

stats.nlink reports the number of hard links to the entry from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

222/268
stats.uid
<number> | <bigint> The numeric user identifier of the user that owns the file (POSIX).

stats.uid reports the numeric user ID of the owner from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

223/268
stats.gid
<number> | <bigint> The numeric group identifier of the group that owns the file (POSIX).

stats.gid reports the numeric group ID of the owner from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

224/268
stats.rdev
<number> | <bigint> A numeric device identifier if the file represents a device.

stats.rdev reports the device identifier for a special device file from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

225/268
stats.size
<number> | <bigint> The size of the file in bytes. If the underlying file system does not support getting the size of the file,this will be 0.

size is the length of the file in bytes, as reported by the filesystem at the time of the stat call. It is not the number of bytes already read by a stream. File contents can change after the metadata snapshot.

226/268
stats.blksize
<number> | <bigint> The file system block size for i/o operations.

stats.blksize reports the preferred block size for I/O on this file from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

227/268
stats.blocks
<number> | <bigint> The number of blocks allocated for this file.

stats.blocks reports the number of allocated filesystem blocks from a filesystem metadata snapshot. The value describes the entry at the time of the stat call and can change later. Use the bigint option if these numeric metadata values need bigint representation.

228/268
stats.atimeMs
<number> | <bigint> The timestamp indicating the last time this file was accessed expressed inmilliseconds since the POSIX Epoch.

stats.atimeMs represents the file’s last access time as milliseconds since the Unix epoch. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

229/268
stats.mtimeMs
<number> | <bigint> The timestamp indicating the last time this file was modified expressed inmilliseconds since the POSIX Epoch.

stats.mtimeMs represents the file’s last content modification time as milliseconds since the Unix epoch. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

230/268
stats.ctimeMs
<number> | <bigint> The timestamp indicating the last time the file status was changed expressedin milliseconds since the POSIX Epoch.

stats.ctimeMs represents the file’s last metadata change time as milliseconds since the Unix epoch. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

231/268
stats.birthtimeMs
<number> | <bigint> The timestamp indicating the creation time of this file expressed inmilliseconds since the POSIX Epoch.

stats.birthtimeMs represents the file’s creation or birth time as milliseconds since the Unix epoch. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

232/268
stats.atimeNs
<bigint> Only present when bigint: true is passed into the method that generatesthe object.The timestamp indicating the last time this file was accessed expressed innanoseconds since the POSIX Epoch.
233/268
stats.mtimeNs
<bigint> Only present when bigint: true is passed into the method that generatesthe object.The timestamp indicating the last time this file was modified expressed innanoseconds since the POSIX Epoch.
234/268
stats.ctimeNs
<bigint> Only present when bigint: true is passed into the method that generatesthe object.The timestamp indicating the last time the file status was changed expressedin nanoseconds since the POSIX Epoch.
235/268
stats.birthtimeNs
<bigint> Only present when bigint: true is passed into the method that generatesthe object.The timestamp indicating the creation time of this file expressed innanoseconds since the POSIX Epoch.

stats.birthtimeNs represents the file’s creation or birth time as nanoseconds since the Unix epoch. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

236/268
stats.atime
<Date> The timestamp indicating the last time this file was accessed.

stats.atime represents the file’s last access time as a Date object. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

237/268
stats.mtime
<Date> The timestamp indicating the last time this file was modified.

stats.mtime represents the file’s last content modification time as a Date object. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

238/268
stats.ctime
<Date> The timestamp indicating the last time the file status was changed.

stats.ctime represents the file’s last metadata change time as a Date object. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

239/268
stats.birthtime
<Date> The timestamp indicating the creation time of this file.

stats.birthtime represents the file’s creation or birth time as a Date object. It comes from a metadata snapshot and may differ across operating systems and filesystems. In particular, ctime means metadata change time, not necessarily file creation time.

240/268
Stat time values
The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties arenumeric values that hold the corresponding times in milliseconds. Theirprecision is platform specific. When bigint: true is passed into themethod that generates the object, the properties will be bigints,otherwise they will be numbers.
241/268
Class: fs.StatFs
Provides information about a mounted file system. Objects returned from fs.statfs() and its synchronous counterpart are ofthis type. If bigint in the options passed to those methods is true, thenumeric values will be bigint instead of number.
242/268
statfs.bavail
<number> | <bigint> Free blocks available to unprivileged users.

statfs.bavail reports the blocks available to unprivileged users in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

243/268
statfs.bfree
<number> | <bigint> Free blocks in file system.

statfs.bfree reports the free blocks on the filesystem in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

244/268
statfs.blocks
<number> | <bigint> Total data blocks in file system.

statfs.blocks reports the total number of blocks on the filesystem in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

245/268
statfs.bsize
<number> | <bigint> Optimal transfer block size.

statfs.bsize reports the filesystem block size in bytes in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

246/268
statfs.ffree
<number> | <bigint> Free file nodes in file system.

statfs.ffree reports the number of free file nodes in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

247/268
statfs.files
<number> | <bigint> Total file nodes in file system.

statfs.files reports the total number of file nodes in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

248/268
statfs.type
<number> | <bigint> Type of file system.

statfs.type reports the filesystem type identifier in an fs.StatFs snapshot. Use fs.statfs() or its Promise/synchronous counterpart to obtain this metadata for a path. The values describe filesystem capacity or type, not the contents of a particular file.

249/268
Class: fs.WriteStream
Extends <stream.Writable> Instances of <fs.WriteStream> are created and returned using thefs.createWriteStream() function.

fs.WriteStream is a writable stream for file data, usually created with fs.createWriteStream(). It accepts chunks and writes them progressively. Handle errors, finish the stream with end(), and use the relevant events to track completion.

250/268
Event: 'close'
Emitted when the <fs.WriteStream>'s underlying file descriptor has been closed.

The WriteStream emits close after its underlying resource has closed. A close event is distinct from finish, which indicates the writable side accepted all data. Handle errors separately and do not infer durable storage solely from close.

251/268
Event: 'open'
fd <integer> Integer file descriptor used by the <fs.WriteStream>. Emitted when the <fs.WriteStream>'s file is opened.

The WriteStream emits open when its file descriptor is opened and passes that descriptor to listeners. It precedes or accompanies readiness to write, but does not mean buffered data has finished writing. Handle errors if opening fails.

252/268
Event: 'ready'
Emitted when the <fs.WriteStream> is ready to be used. Fires immediately after 'open'.

The WriteStream emits ready when it can begin writing after the file is open. It does not mean all writes are complete or synchronized to disk. Use finish and error events to track completion and failures.

253/268
writeStream.bytesWritten
The number of bytes written so far. Does not include data that is still queuedfor writing.

bytesWritten counts bytes written by the WriteStream so far. It is useful for progress reporting, but it is not a promise that data has been durably synchronized to storage. Use sync-related APIs if durability is required.

254/268
writeStream.close([callback])
callback <Function>err <Error> Closes writeStream. Optionally accepts acallback that will be executed once the writeStreamis closed.

This closes a writable file stream; the optional callback runs after closure. End pending writes appropriately before closing if their data must be flushed. The method releases the stream descriptor but does not delete the file.

255/268
writeStream.path
The path to the file the stream is writing to as specified in the firstargument to fs.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>.
256/268
writeStream.pending
<boolean> This property is true if the underlying file has not been opened yet,i.e. before the 'ready' event is emitted.

pending indicates whether the WriteStream is waiting for its underlying file to open. It is not a count of unwritten bytes. Handle the open and error events when coordinating writes or reporting startup failure.

257/268
fs.constants
<Object> Returns an object containing commonly used constants for file systemoperations.

fs.constants contains named flags for access checks, file opening, copying and related operations. For example, F_OK tests existence in access(). Constants describe options; reading this object does not access the filesystem.

258/268
FS constants
The following constants are exported by fs.constants and fsPromises.constants. To use more than one constant, use the bitwise OR | operator. Example:
259/268
Ordering of callback and promise-based operations
Because they are executed asynchronously by the underlying thread pool,there is no guaranteed ordering when using either the callback orpromise-based methods. For example, the following is prone to error because the fs.stat()operation might complete before the fs.rename() operation:
260/268
File paths
Most fs operations accept file paths that may be specified in the form ofa string, a <Buffer>, or a <URL> object using the file: protocol.

Node file-system APIs accept several path representations, including strings, Buffers and file: URLs where documented. Relative paths are resolved against the process working directory, not automatically against the source file. Normalize or resolve paths for the intended base directory.

261/268
String paths
String paths are interpreted as UTF-8 character sequences identifyingthe absolute or relative filename. Relative paths will be resolved relativeto the current working directory as determined by calling process.cwd(). Example using an absolute path on POSIX:
262/268
File URL paths
For most node:fs module functions, the path or filename argument may bepassed as a <URL> object using the file: protocol.
263/268
Buffer paths
Paths specified using a <Buffer> are useful primarily on certain POSIXoperating systems that treat file paths as opaque byte sequences. On suchsystems, it is possible for a single file path to contain sub-sequences thatuse multiple character encodings. As with string paths, <Buffer> paths maybe relative or absolute:
264/268
Per-drive working directories on Windows
On Windows, Node.js follows the concept of per-drive working directory. Thisbehavior can be observed when using a drive path without a backslash. Forexample fs.readdirSync('C:\\') can potentially return a different result thanfs.readdirSync('C:'). For more information, seethis MSDN page.
265/268
File descriptors
On POSIX systems, for every process, the kernel maintains a table of currentlyopen files and resources. Each open file is assigned a simple numericidentifier called a file descriptor. At the system-level, all file systemoperations use these file descriptors to identify and track each specificfile. Windows systems use a different but conceptually similar mechanism fortracking resources. To simplify things for users, Node.js abstracts away thedifferences between operating systems and assigns all open files a numeric filedescriptor.
266/268
Threadpool usage
All callback and promise-based file system APIs (with the exception offs.FSWatcher()) use libuv's threadpool. This can have surprising and negativeperformance implications for some applications. See theUV_THREADPOOL_SIZE documentation for more information.
267/268
File system flags
The following flags are available wherever the flag option takes astring. 'a': Open file for appending.The file is created if it does not exist. 'ax': Like 'a' but fails if the path exists. 'a+': Open file for reading and appending.The file is created if it does not exist.
268/268