Node.js File System Module

The pack contained all methos of the file system in node js, the cards with methods description and code examples. Start learning process to getting cards direct to your messenger in case to learn node fs from scratch or fill up your technical gaps.

You can start studying this pack. You'll receive 1072 messages to help you review each card multiple times, following the principles of the forgetting curve.

Learn more about the spaced repetition method.

Schedule daily card reviews to quickly memorize or solidify the knowledge until it becomes second nature.

Learn more about daily practices.
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.
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.
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.

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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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.
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().
139/268
fs.futimesSync(fd, atime, mtime)
fd <integer> atime <number> | <string> | <Date> mtime <number> | <string> | <Date> Synchronous version of fs.futimes(). Returns undefined.
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.
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.
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().
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.
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().
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).
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.
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.
177/268
dir.path
<string> The read-only path of this directory as was provided to fs.opendir(),fs.opendirSync(), or fsPromises.opendir().
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.
184/268
dirent.isCharacterDevice()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a character device.
185/268
dirent.isDirectory()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a file systemdirectory.
186/268
dirent.isFIFO()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a first-in-first-out(FIFO) pipe.
187/268
dirent.isFile()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a regular file.
188/268
dirent.isSocket()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a socket.
189/268
dirent.isSymbolicLink()
Returns: <boolean> Returns true if the <fs.Dirent> object describes a symbolic link.
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().
191/268
dirent.parentPath
<string> The path to the parent directory of the file this <fs.Dirent> object refers to.
192/268
dirent.path
<string> Alias for dirent.parentPath.
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.
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.
197/268
watcher.close()
Stop watching for changes on the given <fs.FSWatcher>. Once stopped, the<fs.FSWatcher> object is no longer usable.
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.
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.
204/268
Event: 'close'
Emitted when the <fs.ReadStream>'s underlying file descriptor has been closed.
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.
206/268
Event: 'ready'
Emitted when the <fs.ReadStream> is ready to be used. Fires immediately after 'open'.
207/268
readStream.bytesRead
<number> The number of bytes that have been read so far.
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.
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.
212/268
stats.isCharacterDevice()
Returns: <boolean> Returns true if the <fs.Stats> object describes a character device.
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.
215/268
stats.isFile()
Returns: <boolean> Returns true if the <fs.Stats> object describes a regular file.
216/268
stats.isSocket()
Returns: <boolean> Returns true if the <fs.Stats> object describes a socket.
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().
218/268
stats.dev
<number> | <bigint> The numeric identifier of the device containing the file.
219/268
stats.ino
<number> | <bigint> The file system specific "Inode" number for the file.
220/268
stats.mode
<number> | <bigint> A bit-field describing the file type and mode.
221/268
stats.nlink
<number> | <bigint> The number of hard-links that exist for the file.
222/268
stats.uid
<number> | <bigint> The numeric user identifier of the user that owns the file (POSIX).
223/268
stats.gid
<number> | <bigint> The numeric group identifier of the group that owns the file (POSIX).
224/268
stats.rdev
<number> | <bigint> A numeric device identifier if the file represents a device.
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.
226/268
stats.blksize
<number> | <bigint> The file system block size for i/o operations.
227/268
stats.blocks
<number> | <bigint> The number of blocks allocated for this file.
228/268
stats.atimeMs
<number> | <bigint> The timestamp indicating the last time this file was accessed expressed inmilliseconds since the POSIX Epoch.
229/268
stats.mtimeMs
<number> | <bigint> The timestamp indicating the last time this file was modified expressed inmilliseconds since the POSIX Epoch.
230/268
stats.ctimeMs
<number> | <bigint> The timestamp indicating the last time the file status was changed expressedin milliseconds since the POSIX Epoch.
231/268
stats.birthtimeMs
<number> | <bigint> The timestamp indicating the creation time of this file expressed inmilliseconds since the POSIX Epoch.
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.
236/268
stats.atime
<Date> The timestamp indicating the last time this file was accessed.
237/268
stats.mtime
<Date> The timestamp indicating the last time this file was modified.
238/268
stats.ctime
<Date> The timestamp indicating the last time the file status was changed.
239/268
stats.birthtime
<Date> The timestamp indicating the creation time of this file.
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.
243/268
statfs.bfree
<number> | <bigint> Free blocks in file system.
244/268
statfs.blocks
<number> | <bigint> Total data blocks in file system.
245/268
statfs.bsize
<number> | <bigint> Optimal transfer block size.
246/268
statfs.ffree
<number> | <bigint> Free file nodes in file system.
247/268
statfs.files
<number> | <bigint> Total file nodes in file system.
248/268
statfs.type
<number> | <bigint> Type of file system.
249/268
Class: fs.WriteStream
Extends <stream.Writable> Instances of <fs.WriteStream> are created and returned using thefs.createWriteStream() function.
250/268
Event: 'close'
Emitted when the <fs.WriteStream>'s underlying file descriptor has been closed.
251/268
Event: 'open'
fd <integer> Integer file descriptor used by the <fs.WriteStream>. Emitted when the <fs.WriteStream>'s file is opened.
252/268
Event: 'ready'
Emitted when the <fs.WriteStream> is ready to be used. Fires immediately after 'open'.
253/268
writeStream.bytesWritten
The number of bytes written so far. Does not include data that is still queuedfor writing.
254/268
writeStream.close([callback])
callback <Function>err <Error> Closes writeStream. Optionally accepts acallback that will be executed once the writeStreamis closed.
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.
257/268
fs.constants
<Object> Returns an object containing commonly used constants for file systemoperations.
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.
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
WitSlice © 2026