Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
Node.js module
fs
The 'node:fs'
module provides file system I/O operations, including reading, writing, renaming, and deleting files and directories. It offers both synchronous and asynchronous methods.
Works in Bun
Fully implemented. 92% of Node.js's test suite passes.
namespace constants
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.
Constant for fs.access(). File is visible to the calling process.
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.
Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
Constant for fs.open(). Flag indicating to open a file for read-only access.
Constant for fs.open(). Flag indicating to open a file for read-write access.
Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
Constant for fs.open(). Flag indicating to open a file for write-only access.
Constant for fs.access(). File can be read by the calling process.
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.
Constant for fs.access(). File can be written by the calling process.
Constant for fs.access(). File can be executed by the calling process.
- callback: (err: null | ErrnoException, resolvedPath: string) => void): void;
Asynchronously computes the canonical pathname by resolving
.
,..
, and symbolic links.A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.
This function behaves like
realpath(3)
, with some exceptions:- No case conversion is performed on case-insensitive file systems.
- The maximum number of symbolic links is platform-independent and generally (much) higher than what the native
realpath(3)
implementation supports.
The
callback
gets two arguments(err, resolvedPath)
. May useprocess.cwd
to resolve relative paths.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.If
path
resolves to a socket or a pipe, the function will return a system dependent name for that object.): void;Asynchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.): void;Asynchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.namespace realpath
- callback: (err: null | ErrnoException, resolvedPath: string) => void): void;
Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: string) => void): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.
- ): string;
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of this API: realpath.
Synchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.Synchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.namespace realpathSync
class Dir
A class representing a directory stream.
Created by opendir, opendirSync, or
fsPromises.opendir()
.import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); for await (const dirent of dir) console.log(dirent.name); } catch (err) { console.error(err); }
When using the async iterator, the
fs.Dir
object will be automatically closed after the iterator exits.- readonly path: string
The read-only path of this directory as was provided to opendir,opendirSync, or
fsPromises.opendir()
. Asynchronously iterates over the directory via
readdir(3)
until all entries have been read.Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors.
A promise is returned that will be fulfilled after the resource has been closed.
): void;Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors.
A promise is returned that will be fulfilled after the resource has been closed.
Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors.
Asynchronously read the next directory entry via
readdir(3)
as anfs.Dirent
.A promise is returned that will be fulfilled with an
fs.Dirent
, ornull
if there are no more directory entries to read.Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
@returnscontaining {fs.Dirent|null}
read(): void;Asynchronously read the next directory entry via
readdir(3)
as anfs.Dirent
.A promise is returned that will be fulfilled with an
fs.Dirent
, ornull
if there are no more directory entries to read.Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
@returnscontaining {fs.Dirent|null}
Synchronously read the next directory entry as an
fs.Dirent
. See the POSIXreaddir(3)
documentation for more detail.If there are no more directory entries to read,
null
will be returned.Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
class Dirent
A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an
fs.Dir
. The directory entry is a combination of the file name and file type pairs.Additionally, when readdir or readdirSync is called with the
withFileTypes
option set totrue
, the resulting array is filled withfs.Dirent
objects, rather than strings orBuffer
s.- name: string
The file name that this
fs.Dirent
object refers to. The type of this value is determined by theoptions.encoding
passed to readdir or readdirSync. Returns
true
if thefs.Dirent
object describes a block device.Returns
true
if thefs.Dirent
object describes a character device.Returns
true
if thefs.Dirent
object describes a file system directory.Returns
true
if thefs.Dirent
object describes a first-in-first-out (FIFO) pipe.Returns
true
if thefs.Dirent
object describes a regular file.Returns
true
if thefs.Dirent
object describes a socket.Returns
true
if thefs.Dirent
object describes a symbolic link.
class ReadStream
Instances of
fs.ReadStream
are created and returned using the createReadStream function.- path: string | Buffer<ArrayBufferLike>
The path to the file the stream is reading from as specified in the first argument to
fs.createReadStream()
. Ifpath
is passed as a string, thenreadStream.path
will be a string. Ifpath
is passed as aBuffer
, thenreadStream.path
will be aBuffer
. Iffd
is specified, thenreadStream.path
will beundefined
. - pending: boolean
This property is
true
if the underlying file has not been opened yet, i.e. before the'ready'
event is emitted. - readable: boolean
Is
true
if it is safe to call read, which means the stream has not been destroyed or emitted'error'
or'end'
. - readonly readableAborted: boolean
Returns whether the stream was destroyed or errored before emitting
'end'
. - readonly readableEncoding: null | BufferEncoding
Getter for the property
encoding
of a givenReadable
stream. Theencoding
property can be set using the setEncoding method. - readonly readableFlowing: null | boolean
This property reflects the current state of a
Readable
stream as described in the Three states section. - readonly readableHighWaterMark: number
Returns the value of
highWaterMark
passed when creating thisReadable
. - readonly readableLength: number
This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the
highWaterMark
. - static captureRejections: boolean
Value: boolean
Change the default
captureRejections
option on all newEventEmitter
objects. - readonly static captureRejectionSymbol: typeof captureRejectionSymbol
Value:
Symbol.for('nodejs.rejection')
See how to write a custom
rejection handler
. - static defaultMaxListeners: number
By default, a maximum of
10
listeners can be registered for any single event. This limit can be changed for individualEventEmitter
instances using theemitter.setMaxListeners(n)
method. To change the default for allEventEmitter
instances, theevents.defaultMaxListeners
property can be used. If this value is not a positive number, aRangeError
is thrown.Take caution when setting the
events.defaultMaxListeners
because the change affects allEventEmitter
instances, including those created before the change is made. However, callingemitter.setMaxListeners(n)
still has precedence overevents.defaultMaxListeners
.This is not a hard limit. The
EventEmitter
instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter
, theemitter.getMaxListeners()
andemitter.setMaxListeners()
methods can be used to temporarily avoid this warning:import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); });
The
--trace-warnings
command-line flag can be used to display the stack trace for such warnings.The emitted warning can be inspected with
process.on('warning')
and will have the additionalemitter
,type
, andcount
properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Itsname
property is set to'MaxListenersExceededWarning'
. - readonly static errorMonitor: typeof errorMonitor
This symbol shall be used to install a listener for only monitoring
'error'
events. Listeners installed using this symbol are called before the regular'error'
listeners are called.Installing a listener using this symbol does not change the behavior once an
'error'
event is emitted. Therefore, the process will still crash if no regular'error'
listener is installed. Calls
readable.destroy()
with anAbortError
and returns a promise that fulfills when the stream is finished.- addListener<K extends symbol | 'close' | 'error' | 'data' | 'end' | 'pause' | 'readable' | 'resume' | string & {} | 'open' | 'ready'>(event: K,listener: ReadStreamEvents[K]): this;
events.EventEmitter
- open
- close
- ready
This method returns a new stream with chunks of the underlying stream paired with a counter in the form
[index, chunk]
. The first index value is0
and it increases by 1 for each chunk produced.@returnsa stream of indexed pairs.
- stream: ComposeFnParam | T | Iterable<T, any, any> | AsyncIterable<T, any, any>,): T;
- ): this;
Destroy the stream. Optionally emit an
'error'
event, and emit a'close'
event (unlessemitClose
is set tofalse
). After this call, the readable stream will release any internal resources and subsequent calls topush()
will be ignored.Once
destroy()
has been called any further calls will be a no-op and no further errors except from_destroy()
may be emitted as'error'
.Implementors should not override this method, but instead implement
readable._destroy()
.@param errorError which will be passed as payload in
'error'
event - drop(limit: number,
This method returns a new stream with the first limit chunks dropped from the start.
@param limitthe number of chunks to drop from the readable.
@returnsa stream with limit chunks dropped from the start.
- emit(event: 'close'): boolean;
Synchronously calls each of the listeners registered for the event named
eventName
, in the order they were registered, passing the supplied arguments to each.Returns
true
if the event had listeners,false
otherwise.import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener
Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbol
s.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]
- ): Promise<boolean>;
This method is similar to
Array.prototype.every
and calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunkawait
ed return value is falsy, the stream is destroyed and the promise is fulfilled withfalse
. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled withtrue
.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to
true
if fn returned a truthy value for every one of the chunks. This method allows filtering the stream. For each chunk in the stream the fn function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the fn function returns a promise - that promise will be
await
ed.@param fna function to filter chunks from the stream. Async or not.
@returnsa stream filtered with the predicate fn.
- ): Promise<undefined | T>;
This method is similar to
Array.prototype.find
and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled withundefined
.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to the first chunk for which fn evaluated with a truthy value, or
undefined
if no element was found.find(): Promise<any>;This method is similar to
Array.prototype.find
and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled withundefined
.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to the first chunk for which fn evaluated with a truthy value, or
undefined
if no element was found. This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.
It is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.
@param fna function to map over every chunk in the stream. May be async. May be a stream or generator.
@returnsa stream flat-mapped with the function fn.
- ): Promise<void>;
This method allows iterating a stream. For each chunk in the stream the fn function will be called. If the fn function returns a promise - that promise will be
await
ed.This method is different from
for await...of
loops in that it can optionally process chunks concurrently. In addition, aforEach
iteration can only be stopped by having passed asignal
option and aborting the related AbortController whilefor await...of
can be stopped withbreak
orreturn
. In either case the stream will be destroyed.This method is different from listening to the
'data'
event in that it uses thereadable
event in the underlying machinary and can limit the number of concurrent fn calls.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise for when the stream has finished.
Returns the current max listener value for the
EventEmitter
which is either set byemitter.setMaxListeners(n)
or defaults to EventEmitter.defaultMaxListeners.The
readable.isPaused()
method returns the current operating state of theReadable
. This is used primarily by the mechanism that underlies thereadable.pipe()
method. In most typical cases, there will be no reason to use this method directly.const readable = new stream.Readable(); readable.isPaused(); // === false readable.pause(); readable.isPaused(); // === true readable.resume(); readable.isPaused(); // === false
- options?: { destroyOnReturn: boolean }): AsyncIterator<any>;
The iterator created by this method gives users the option to cancel the destruction of the stream if the
for await...of
loop is exited byreturn
,break
, orthrow
, or if the iterator should destroy the stream if the stream emitted an error during iteration. - eventName: string | symbol,listener?: Function): number;
Returns the number of listeners listening for the event named
eventName
. Iflistener
is provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
.server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ]
- map(
This method allows mapping over the stream. The fn function will be called for every chunk in the stream. If the fn function returns a promise - that promise will be
await
ed before being passed to the result stream.@param fna function to map over every chunk in the stream. Async or not.
@returnsa stream mapped with the function fn.
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.removeListener()
. - on<K extends symbol | 'close' | 'error' | 'data' | 'end' | 'pause' | 'readable' | 'resume' | string & {} | 'open' | 'ready'>(event: K,listener: ReadStreamEvents[K]): this;
Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
- once<K extends symbol | 'close' | 'error' | 'data' | 'end' | 'pause' | 'readable' | 'resume' | string & {} | 'open' | 'ready'>(event: K,listener: ReadStreamEvents[K]): this;
Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
The
readable.pause()
method will cause a stream in flowing mode to stop emitting'data'
events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); readable.pause(); console.log('There will be no additional data for 1 second.'); setTimeout(() => { console.log('Now data will start flowing again.'); readable.resume(); }, 1000); });
The
readable.pause()
method has no effect if there is a'readable'
event listener.- prependListener<K extends symbol | 'close' | 'error' | 'data' | 'end' | 'pause' | 'readable' | 'resume' | string & {} | 'open' | 'ready'>(event: K,listener: ReadStreamEvents[K]): this;
Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
- prependOnceListener<K extends symbol | 'close' | 'error' | 'data' | 'end' | 'pause' | 'readable' | 'resume' | string & {} | 'open' | 'ready'>(event: K,listener: ReadStreamEvents[K]): this;
Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
, including any wrappers (such as those created by.once()
).import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log');
- read(size?: number): any;
The
readable.read()
method reads data out of the internal buffer and returns it. If no data is available to be read,null
is returned. By default, the data is returned as aBuffer
object unless an encoding has been specified using thereadable.setEncoding()
method or the stream is operating in object mode.The optional
size
argument specifies a specific number of bytes to read. Ifsize
bytes are not available to be read,null
will be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.If the
size
argument is not specified, all of the data contained in the internal buffer will be returned.The
size
argument must be less than or equal to 1 GiB.The
readable.read()
method should only be called onReadable
streams operating in paused mode. In flowing mode,readable.read()
is called automatically until the internal buffer is fully drained.const readable = getReadableStreamSomehow(); // 'readable' may be triggered multiple times as data is buffered in readable.on('readable', () => { let chunk; console.log('Stream is readable (new data received in buffer)'); // Use a loop to make sure we read all currently available data while (null !== (chunk = readable.read())) { console.log(`Read ${chunk.length} bytes of data...`); } }); // 'end' will be triggered once when there is no more data available readable.on('end', () => { console.log('Reached end of stream.'); });
Each call to
readable.read()
returns a chunk of data, ornull
. The chunks are not concatenated. Awhile
loop is necessary to consume all data currently in the buffer. When reading a large file.read()
may returnnull
, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new'readable'
event will be emitted when there is more data in the buffer. Finally the'end'
event will be emitted when there is no more data to come.Therefore to read a file's whole contents from a
readable
, it is necessary to collect chunks across multiple'readable'
events:const chunks = []; readable.on('readable', () => { let chunk; while (null !== (chunk = readable.read())) { chunks.push(chunk); } }); readable.on('end', () => { const content = chunks.join(''); });
A
Readable
stream in object mode will always return a single item from a call toreadable.read(size)
, regardless of the value of thesize
argument.If the
readable.read()
method returns a chunk of data, a'data'
event will also be emitted.Calling read after the
'end'
event has been emitted will returnnull
. No runtime error will be raised.@param sizeOptional argument to specify how much data to read.
- initial?: undefined,): Promise<T>;
This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a
TypeError
with theERR_INVALID_ARGS
code property.The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to
readable.map
method.@param fna reducer function to call over every chunk in the stream. Async or not.
@param initialthe initial value to use in the reduction.
@returnsa promise for the final value of the reduction.
initial: T,): Promise<T>;This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a
TypeError
with theERR_INVALID_ARGS
code property.The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to
readable.map
method.@param fna reducer function to call over every chunk in the stream. Async or not.
@param initialthe initial value to use in the reduction.
@returnsa promise for the final value of the reduction.
- eventName?: string | symbol): this;
Removes all listeners, or those of the specified
eventName
.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter
instance was created by some other component or module (e.g. sockets or file streams).Returns a reference to the
EventEmitter
, so that calls can be chained. - event: 'close',listener: () => void): this;
Removes the specified
listener
from the listener array for the event namedeventName
.const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
removeListener()
will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specifiedeventName
, thenremoveListener()
must be called multiple times to remove each instance.Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any
removeListener()
orremoveAllListeners()
calls after emitting and before the last listener finishes execution will not remove them fromemit()
in progress. Subsequent events behave as expected.import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the
emitter.listeners()
method will need to be recreated.When a single function has been added as a handler multiple times for a single event (as in the example below),
removeListener()
will remove the most recently added instance. In the example theonce('ping')
listener is removed:import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');
Returns a reference to the
EventEmitter
, so that calls can be chained. The
readable.resume()
method causes an explicitly pausedReadable
stream to resume emitting'data'
events, switching the stream into flowing mode.The
readable.resume()
method can be used to fully consume the data from a stream without actually processing any of that data:getReadableStreamSomehow() .resume() .on('end', () => { console.log('Reached the end, but did not read anything.'); });
The
readable.resume()
method has no effect if there is a'readable'
event listener.- encoding: BufferEncoding): this;
The
readable.setEncoding()
method sets the character encoding for data read from theReadable
stream.By default, no encoding is assigned and stream data will be returned as
Buffer
objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than asBuffer
objects. For instance, callingreadable.setEncoding('utf8')
will cause the output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex')
will cause the data to be encoded in hexadecimal string format.The
Readable
stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream asBuffer
objects.const readable = getReadableStreamSomehow(); readable.setEncoding('utf8'); readable.on('data', (chunk) => { assert.equal(typeof chunk, 'string'); console.log('Got %d characters of string data:', chunk.length); });
@param encodingThe encoding to use.
- n: number): this;
By default
EventEmitter
s will print a warning if more than10
listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()
method allows the limit to be modified for this specificEventEmitter
instance. The value can be set toInfinity
(or0
) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter
, so that calls can be chained. - some(): Promise<boolean>;
This method is similar to
Array.prototype.some
and calls fn on each chunk in the stream until the awaited return value istrue
(or any truthy value). Once an fn call on a chunkawait
ed return value is truthy, the stream is destroyed and the promise is fulfilled withtrue
. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled withfalse
.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to
true
if fn returned a truthy value for at least one of the chunks. - @param limit
the number of chunks to take from the readable.
@returnsa stream with limit chunks taken.
- ): Promise<any[]>;
This method allows easily obtaining the contents of a stream.
As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.
@returnsa promise containing an array with the contents of the stream.
- destination?: WritableStream): this;
The
readable.unpipe()
method detaches aWritable
stream previously attached using the pipe method.If the
destination
is not specified, then all pipes are detached.If the
destination
is specified, but no pipe is set up for it, then the method does nothing.import fs from 'node:fs'; const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', // but only for the first second. readable.pipe(writable); setTimeout(() => { console.log('Stop writing to file.txt.'); readable.unpipe(writable); console.log('Manually close the file stream.'); writable.end(); }, 1000);
@param destinationOptional specific stream to unpipe
- chunk: any,encoding?: BufferEncoding): void;
Passing
chunk
asnull
signals the end of the stream (EOF) and behaves the same asreadable.push(null)
, after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed.The
readable.unshift()
method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.The
stream.unshift(chunk)
method cannot be called after the'end'
event has been emitted or a runtime error will be thrown.Developers using
stream.unshift()
often should consider switching to use of aTransform
stream instead. See theAPI for stream implementers
section for more information.// Pull off a header delimited by \n\n. // Use unshift() if we get too much. // Call the callback with (error, header, stream). import { StringDecoder } from 'node:string_decoder'; function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); const decoder = new StringDecoder('utf8'); let header = ''; function onReadable() { let chunk; while (null !== (chunk = stream.read())) { const str = decoder.write(chunk); if (str.includes('\n\n')) { // Found the header boundary. const split = str.split(/\n\n/); header += split.shift(); const remaining = split.join('\n\n'); const buf = Buffer.from(remaining, 'utf8'); stream.removeListener('error', callback); // Remove the 'readable' listener before unshifting. stream.removeListener('readable', onReadable); if (buf.length) stream.unshift(buf); // Now the body of the message can be read from the stream. callback(null, header, stream); return; } // Still reading the header. header += str; } } }
Unlike push,
stream.unshift(chunk)
will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results ifreadable.unshift()
is called during a read (i.e. from within a _read implementation on a custom stream). Following the call toreadable.unshift()
with an immediate push will reset the reading state appropriately, however it is best to simply avoid callingreadable.unshift()
while in the process of performing a read.@param chunkChunk of data to unshift onto the read queue. For streams not operating in object mode,
chunk
must be a {string}, {Buffer}, {TypedArray}, {DataView} ornull
. For object mode streams,chunk
may be any JavaScript value.@param encodingEncoding of string chunks. Must be a valid
Buffer
encoding, such as'utf8'
or'ascii'
. - wrap(stream: ReadableStream): this;
Prior to Node.js 0.10, streams did not implement the entire
node:stream
module API as it is currently defined. (SeeCompatibility
for more information.)When using an older Node.js library that emits
'data'
events and has a pause method that is advisory only, thereadable.wrap()
method can be used to create aReadable
stream that uses the old stream as its data source.It will rarely be necessary to use
readable.wrap()
but the method has been provided as a convenience for interacting with older Node.js applications and libraries.import { OldReader } from './old-api-module.js'; import { Readable } from 'node:stream'; const oreader = new OldReader(); const myReader = new Readable().wrap(oreader); myReader.on('readable', () => { myReader.read(); // etc. });
@param streamAn "old style" readable stream
- ): Disposable;
Listens once to the
abort
event on the providedsignal
.Listening to the
abort
event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can calle.stopImmediatePropagation()
. Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.This API allows safely using
AbortSignal
s in Node.js APIs by solving these two issues by listening to the event such thatstopImmediatePropagation
does not prevent the listener from running.Returns a disposable so that it may be unsubscribed from more easily.
import { addAbortListener } from 'node:events'; function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } }
@returnsDisposable that removes the
abort
listener. - iterable: Iterable<any, any, any> | AsyncIterable<any, any, any>,
A utility method for creating Readable Streams out of iterators.
@param iterableObject implementing the
Symbol.asyncIterator
orSymbol.iterator
iterable protocol. Emits an 'error' event if a null value is passed.@param optionsOptions provided to
new stream.Readable([options])
. By default,Readable.from()
will setoptions.objectMode
totrue
, unless this is explicitly opted out by settingoptions.objectMode
tofalse
. A utility method for creating a
Readable
from a webReadableStream
.- name: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
.For
EventEmitter
s this behaves exactly the same as calling.listeners
on the emitter.For
EventTarget
s this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.import { getEventListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] }
- ): number;
Returns the currently set max amount of listeners.
For
EventEmitter
s this behaves exactly the same as calling.getMaxListeners
on the emitter.For
EventTarget
s this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 }
- ): boolean;
Returns whether the stream has been read from or cancelled.
- emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterIteratorOptions): AsyncIterator<any[]>;
import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here
Returns an
AsyncIterator
that iterateseventName
events. It will throw if theEventEmitter
emits'error'
. It removes all listeners when exiting the loop. Thevalue
returned by each iteration is an array composed of the emitted event arguments.An
AbortSignal
can be used to cancel waiting on events:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());
Use the
close
option to specify an array of event names that will end the iteration:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close'); }); for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42] } // the loop will exit after 'close' is emitted console.log('done'); // prints 'done'
@returnsAn
AsyncIterator
that iterateseventName
events emitted by theemitter
eventName: string,options?: StaticEventEmitterIteratorOptions): AsyncIterator<any[]>;import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here
Returns an
AsyncIterator
that iterateseventName
events. It will throw if theEventEmitter
emits'error'
. It removes all listeners when exiting the loop. Thevalue
returned by each iteration is an array composed of the emitted event arguments.An
AbortSignal
can be used to cancel waiting on events:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());
Use the
close
option to specify an array of event names that will end the iteration:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close'); }); for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42] } // the loop will exit after 'close' is emitted console.log('done'); // prints 'done'
@returnsAn
AsyncIterator
that iterateseventName
events emitted by theemitter
- emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterOptions): Promise<any[]>;
Creates a
Promise
that is fulfilled when theEventEmitter
emits the given event or that is rejected if theEventEmitter
emits'error'
while waiting. ThePromise
will resolve with an array of all the arguments emitted to the given event.This method is intentionally generic and works with the web platform EventTarget interface, which has no special
'error'
event semantics and does not listen to the'error'
event.import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }
The special handling of the
'error'
event is only used whenevents.once()
is used to wait for another event. Ifevents.once()
is used to wait for the 'error'
event itself, then it is treated as any other kind of event without special handling:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom
An
AbortSignal
can be used to cancel waiting for the event:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled!
eventName: string,options?: StaticEventEmitterOptions): Promise<any[]>;Creates a
Promise
that is fulfilled when theEventEmitter
emits the given event or that is rejected if theEventEmitter
emits'error'
while waiting. ThePromise
will resolve with an array of all the arguments emitted to the given event.This method is intentionally generic and works with the web platform EventTarget interface, which has no special
'error'
event semantics and does not listen to the'error'
event.import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }
The special handling of the
'error'
event is only used whenevents.once()
is used to wait for another event. Ifevents.once()
is used to wait for the 'error'
event itself, then it is treated as any other kind of event without special handling:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom
An
AbortSignal
can be used to cancel waiting for the event:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled!
- n?: number,): void;
import { setMaxListeners, EventEmitter } from 'node:events'; const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter);
@param nA non-negative number. The maximum number of listeners per
EventTarget
event.@param eventTargetsZero or more {EventTarget} or {EventEmitter} instances. If none are specified,
n
is set as the default max for all newly created {EventTarget} and {EventEmitter} objects. A utility method for creating a web
ReadableStream
from aReadable
.
class Stats
A
fs.Stats
object provides information about a file.Objects returned from stat, lstat, fstat, and their synchronous counterparts are of this type. If
bigint
in theoptions
passed to those methods is true, the numeric values will bebigint
instead ofnumber
, and the object will contain additional nanosecond-precision properties suffixed withNs
.Stat
objects are not to be created directly using thenew
keyword.Stats { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 527, blksize: 4096, blocks: 8, atimeMs: 1318289051000.1, mtimeMs: 1318289051000.1, ctimeMs: 1318289051000.1, birthtimeMs: 1318289051000.1, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
bigint
version:BigIntStats { dev: 2114n, ino: 48064969n, mode: 33188n, nlink: 1n, uid: 85n, gid: 100n, rdev: 0n, size: 527n, blksize: 4096n, blocks: 8n, atimeMs: 1318289051000n, mtimeMs: 1318289051000n, ctimeMs: 1318289051000n, birthtimeMs: 1318289051000n, atimeNs: 1318289051000000000n, mtimeNs: 1318289051000000000n, ctimeNs: 1318289051000000000n, birthtimeNs: 1318289051000000000n, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
class StatsFs
Provides information about a mounted file system.
Objects returned from statfs and its synchronous counterpart are of this type. If
bigint
in theoptions
passed to those methods istrue
, the numeric values will bebigint
instead ofnumber
.StatFs { type: 1397114950, bsize: 4096, blocks: 121938943, bfree: 61058895, bavail: 61058895, files: 999, ffree: 1000000 }
bigint
version:StatFs { type: 1397114950n, bsize: 4096n, blocks: 121938943n, bfree: 61058895n, bavail: 61058895n, files: 999n, ffree: 1000000n }
class WriteStream
- Extends
stream.Writable
Instances of
fs.WriteStream
are created and returned using the createWriteStream function.- bytesWritten: number
The number of bytes written so far. Does not include data that is still queued for writing.
- pending: boolean
This property is
true
if the underlying file has not been opened yet, i.e. before the'ready'
event is emitted. - readonly writable: boolean
Is
true
if it is safe to callwritable.write()
, which means the stream has not been destroyed, errored, or ended. - readonly writableCorked: number
Number of times
writable.uncork()
needs to be called in order to fully uncork the stream. - readonly writableEnded: boolean
Is
true
afterwritable.end()
has been called. This property does not indicate whether the data has been flushed, for this usewritable.writableFinished
instead. - readonly writableHighWaterMark: number
Return the value of
highWaterMark
passed when creating thisWritable
. - readonly writableLength: number
This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the
highWaterMark
. - readonly writableNeedDrain: boolean
Is
true
if the stream's buffer has been full and stream will emit'drain'
. - static captureRejections: boolean
Value: boolean
Change the default
captureRejections
option on all newEventEmitter
objects. - readonly static captureRejectionSymbol: typeof captureRejectionSymbol
Value:
Symbol.for('nodejs.rejection')
See how to write a custom
rejection handler
. - static defaultMaxListeners: number
By default, a maximum of
10
listeners can be registered for any single event. This limit can be changed for individualEventEmitter
instances using theemitter.setMaxListeners(n)
method. To change the default for allEventEmitter
instances, theevents.defaultMaxListeners
property can be used. If this value is not a positive number, aRangeError
is thrown.Take caution when setting the
events.defaultMaxListeners
because the change affects allEventEmitter
instances, including those created before the change is made. However, callingemitter.setMaxListeners(n)
still has precedence overevents.defaultMaxListeners
.This is not a hard limit. The
EventEmitter
instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter
, theemitter.getMaxListeners()
andemitter.setMaxListeners()
methods can be used to temporarily avoid this warning:import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); });
The
--trace-warnings
command-line flag can be used to display the stack trace for such warnings.The emitted warning can be inspected with
process.on('warning')
and will have the additionalemitter
,type
, andcount
properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Itsname
property is set to'MaxListenersExceededWarning'
. - readonly static errorMonitor: typeof errorMonitor
This symbol shall be used to install a listener for only monitoring
'error'
events. Listeners installed using this symbol are called before the regular'error'
listeners are called.Installing a listener using this symbol does not change the behavior once an
'error'
event is emitted. Therefore, the process will still crash if no regular'error'
listener is installed. - addListener<K extends symbol | 'pipe' | 'close' | 'error' | 'drain' | 'finish' | 'unpipe' | string & {} | 'open' | 'ready'>(event: K,listener: WriteStreamEvents[K]): this;
events.EventEmitter
- open
- close
- ready
- callback?: (err?: null | ErrnoException) => void): void;
Closes
writeStream
. Optionally accepts a callback that will be executed once thewriteStream
is closed. - stream: ComposeFnParam | T | Iterable<T, any, any> | AsyncIterable<T, any, any>,): T;
The
writable.cork()
method forces all written data to be buffered in memory. The buffered data will be flushed when either the uncork or end methods are called.The primary intent of
writable.cork()
is to accommodate a situation in which several small chunks are written to the stream in rapid succession. Instead of immediately forwarding them to the underlying destination,writable.cork()
buffers all the chunks untilwritable.uncork()
is called, which will pass them all towritable._writev()
, if present. This prevents a head-of-line blocking situation where data is being buffered while waiting for the first small chunk to be processed. However, use ofwritable.cork()
without implementingwritable._writev()
may have an adverse effect on throughput.See also:
writable.uncork()
,writable._writev()
.- ): this;
Destroy the stream. Optionally emit an
'error'
event, and emit a'close'
event (unlessemitClose
is set tofalse
). After this call, the writable stream has ended and subsequent calls towrite()
orend()
will result in anERR_STREAM_DESTROYED
error. This is a destructive and immediate way to destroy a stream. Previous calls towrite()
may not have drained, and may trigger anERR_STREAM_DESTROYED
error. Useend()
instead of destroy if data should flush before close, or wait for the'drain'
event before destroying the stream.Once
destroy()
has been called any further calls will be a no-op and no further errors except from_destroy()
may be emitted as'error'
.Implementors should not override this method, but instead implement
writable._destroy()
.@param errorOptional, an error to emit with
'error'
event. - emit(event: 'close'): boolean;
Synchronously calls each of the listeners registered for the event named
eventName
, in the order they were registered, passing the supplied arguments to each.Returns
true
if the event had listeners,false
otherwise.import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener
- end(cb?: () => void): this;
Calling the
writable.end()
method signals that no more data will be written to theWritable
. The optionalchunk
andencoding
arguments allow one final additional chunk of data to be written immediately before closing the stream.Calling the write method after calling end will raise an error.
// Write 'hello, ' and then end with 'world!'. import fs from 'node:fs'; const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // Writing more now is not allowed!
end(chunk: any,cb?: () => void): this;Calling the
writable.end()
method signals that no more data will be written to theWritable
. The optionalchunk
andencoding
arguments allow one final additional chunk of data to be written immediately before closing the stream.Calling the write method after calling end will raise an error.
// Write 'hello, ' and then end with 'world!'. import fs from 'node:fs'; const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // Writing more now is not allowed!
@param chunkOptional data to write. For streams not operating in object mode,
chunk
must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunk
may be any JavaScript value other thannull
.end(chunk: any,encoding: BufferEncoding,cb?: () => void): this;Calling the
writable.end()
method signals that no more data will be written to theWritable
. The optionalchunk
andencoding
arguments allow one final additional chunk of data to be written immediately before closing the stream.Calling the write method after calling end will raise an error.
// Write 'hello, ' and then end with 'world!'. import fs from 'node:fs'; const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // Writing more now is not allowed!
@param chunkOptional data to write. For streams not operating in object mode,
chunk
must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunk
may be any JavaScript value other thannull
.@param encodingThe encoding if
chunk
is a string Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbol
s.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the
EventEmitter
which is either set byemitter.setMaxListeners(n)
or defaults to EventEmitter.defaultMaxListeners.- eventName: string | symbol,listener?: Function): number;
Returns the number of listeners listening for the event named
eventName
. Iflistener
is provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
.server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ]
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.removeListener()
. - on<K extends symbol | 'pipe' | 'close' | 'error' | 'drain' | 'finish' | 'unpipe' | string & {} | 'open' | 'ready'>(event: K,listener: WriteStreamEvents[K]): this;
Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
- once<K extends symbol | 'pipe' | 'close' | 'error' | 'drain' | 'finish' | 'unpipe' | string & {} | 'open' | 'ready'>(event: K,listener: WriteStreamEvents[K]): this;
Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
- prependListener<K extends symbol | 'pipe' | 'close' | 'error' | 'drain' | 'finish' | 'unpipe' | string & {} | 'open' | 'ready'>(event: K,listener: WriteStreamEvents[K]): this;
Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
- prependOnceListener<K extends symbol | 'pipe' | 'close' | 'error' | 'drain' | 'finish' | 'unpipe' | string & {} | 'open' | 'ready'>(event: K,listener: WriteStreamEvents[K]): this;
Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
, including any wrappers (such as those created by.once()
).import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log');
- eventName?: string | symbol): this;
Removes all listeners, or those of the specified
eventName
.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter
instance was created by some other component or module (e.g. sockets or file streams).Returns a reference to the
EventEmitter
, so that calls can be chained. - event: 'close',listener: () => void): this;
Removes the specified
listener
from the listener array for the event namedeventName
.const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
removeListener()
will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specifiedeventName
, thenremoveListener()
must be called multiple times to remove each instance.Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any
removeListener()
orremoveAllListeners()
calls after emitting and before the last listener finishes execution will not remove them fromemit()
in progress. Subsequent events behave as expected.import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the
emitter.listeners()
method will need to be recreated.When a single function has been added as a handler multiple times for a single event (as in the example below),
removeListener()
will remove the most recently added instance. In the example theonce('ping')
listener is removed:import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');
Returns a reference to the
EventEmitter
, so that calls can be chained. - encoding: BufferEncoding): this;
The
writable.setDefaultEncoding()
method sets the defaultencoding
for aWritable
stream.@param encodingThe new default encoding
- n: number): this;
By default
EventEmitter
s will print a warning if more than10
listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()
method allows the limit to be modified for this specificEventEmitter
instance. The value can be set toInfinity
(or0
) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter
, so that calls can be chained. The
writable.uncork()
method flushes all data buffered since cork was called.When using
writable.cork()
andwritable.uncork()
to manage the buffering of writes to a stream, defer calls towritable.uncork()
usingprocess.nextTick()
. Doing so allows batching of allwritable.write()
calls that occur within a given Node.js event loop phase.stream.cork(); stream.write('some '); stream.write('data '); process.nextTick(() => stream.uncork());
If the
writable.cork()
method is called multiple times on a stream, the same number of calls towritable.uncork()
must be called to flush the buffered data.stream.cork(); stream.write('some '); stream.cork(); stream.write('data '); process.nextTick(() => { stream.uncork(); // The data will not be flushed until uncork() is called a second time. stream.uncork(); });
See also:
writable.cork()
.- chunk: any,): boolean;
The
writable.write()
method writes some data to the stream, and calls the suppliedcallback
once the data has been fully handled. If an error occurs, thecallback
will be called with the error as its first argument. Thecallback
is called asynchronously and before'error'
is emitted.The return value is
true
if the internal buffer is less than thehighWaterMark
configured when the stream was created after admittingchunk
. Iffalse
is returned, further attempts to write data to the stream should stop until the'drain'
event is emitted.While a stream is not draining, calls to
write()
will bufferchunk
, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the'drain'
event will be emitted. Oncewrite()
returns false, do not write more chunks until the'drain'
event is emitted. While callingwrite()
on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.Writing data while the stream is not draining is particularly problematic for a
Transform
, because theTransform
streams are paused by default until they are piped or a'data'
or'readable'
event handler is added.If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a
Readable
and use pipe. However, if callingwrite()
is preferred, it is possible to respect backpressure and avoid memory issues using the'drain'
event:function write(data, cb) { if (!stream.write(data)) { stream.once('drain', cb); } else { process.nextTick(cb); } } // Wait for cb to be called before doing any other write. write('hello', () => { console.log('Write completed, do more writes now.'); });
A
Writable
stream in object mode will always ignore theencoding
argument.@param chunkOptional data to write. For streams not operating in object mode,
chunk
must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunk
may be any JavaScript value other thannull
.@param callbackCallback for when this chunk of data is flushed.
@returnsfalse
if the stream wishes for the calling code to wait for the'drain'
event to be emitted before continuing to write additional data; otherwisetrue
.chunk: any,encoding: BufferEncoding,): boolean;The
writable.write()
method writes some data to the stream, and calls the suppliedcallback
once the data has been fully handled. If an error occurs, thecallback
will be called with the error as its first argument. Thecallback
is called asynchronously and before'error'
is emitted.The return value is
true
if the internal buffer is less than thehighWaterMark
configured when the stream was created after admittingchunk
. Iffalse
is returned, further attempts to write data to the stream should stop until the'drain'
event is emitted.While a stream is not draining, calls to
write()
will bufferchunk
, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the'drain'
event will be emitted. Oncewrite()
returns false, do not write more chunks until the'drain'
event is emitted. While callingwrite()
on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.Writing data while the stream is not draining is particularly problematic for a
Transform
, because theTransform
streams are paused by default until they are piped or a'data'
or'readable'
event handler is added.If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a
Readable
and use pipe. However, if callingwrite()
is preferred, it is possible to respect backpressure and avoid memory issues using the'drain'
event:function write(data, cb) { if (!stream.write(data)) { stream.once('drain', cb); } else { process.nextTick(cb); } } // Wait for cb to be called before doing any other write. write('hello', () => { console.log('Write completed, do more writes now.'); });
A
Writable
stream in object mode will always ignore theencoding
argument.@param chunkOptional data to write. For streams not operating in object mode,
chunk
must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunk
may be any JavaScript value other thannull
.@param encodingThe encoding, if
chunk
is a string.@param callbackCallback for when this chunk of data is flushed.
@returnsfalse
if the stream wishes for the calling code to wait for the'drain'
event to be emitted before continuing to write additional data; otherwisetrue
. - ): Disposable;
Listens once to the
abort
event on the providedsignal
.Listening to the
abort
event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can calle.stopImmediatePropagation()
. Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.This API allows safely using
AbortSignal
s in Node.js APIs by solving these two issues by listening to the event such thatstopImmediatePropagation
does not prevent the listener from running.Returns a disposable so that it may be unsubscribed from more easily.
import { addAbortListener } from 'node:events'; function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } }
@returnsDisposable that removes the
abort
listener. - options?: Pick<WritableOptions<Writable>, 'signal' | 'decodeStrings' | 'highWaterMark' | 'objectMode'>
A utility method for creating a
Writable
from a webWritableStream
. - name: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
.For
EventEmitter
s this behaves exactly the same as calling.listeners
on the emitter.For
EventTarget
s this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.import { getEventListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] }
- ): number;
Returns the currently set max amount of listeners.
For
EventEmitter
s this behaves exactly the same as calling.getMaxListeners
on the emitter.For
EventTarget
s this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 }
- emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterIteratorOptions): AsyncIterator<any[]>;
import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here
Returns an
AsyncIterator
that iterateseventName
events. It will throw if theEventEmitter
emits'error'
. It removes all listeners when exiting the loop. Thevalue
returned by each iteration is an array composed of the emitted event arguments.An
AbortSignal
can be used to cancel waiting on events:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());
Use the
close
option to specify an array of event names that will end the iteration:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close'); }); for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42] } // the loop will exit after 'close' is emitted console.log('done'); // prints 'done'
@returnsAn
AsyncIterator
that iterateseventName
events emitted by theemitter
eventName: string,options?: StaticEventEmitterIteratorOptions): AsyncIterator<any[]>;import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here
Returns an
AsyncIterator
that iterateseventName
events. It will throw if theEventEmitter
emits'error'
. It removes all listeners when exiting the loop. Thevalue
returned by each iteration is an array composed of the emitted event arguments.An
AbortSignal
can be used to cancel waiting on events:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());
Use the
close
option to specify an array of event names that will end the iteration:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close'); }); for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42] } // the loop will exit after 'close' is emitted console.log('done'); // prints 'done'
@returnsAn
AsyncIterator
that iterateseventName
events emitted by theemitter
- emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterOptions): Promise<any[]>;
Creates a
Promise
that is fulfilled when theEventEmitter
emits the given event or that is rejected if theEventEmitter
emits'error'
while waiting. ThePromise
will resolve with an array of all the arguments emitted to the given event.This method is intentionally generic and works with the web platform EventTarget interface, which has no special
'error'
event semantics and does not listen to the'error'
event.import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }
The special handling of the
'error'
event is only used whenevents.once()
is used to wait for another event. Ifevents.once()
is used to wait for the 'error'
event itself, then it is treated as any other kind of event without special handling:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom
An
AbortSignal
can be used to cancel waiting for the event:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled!
eventName: string,options?: StaticEventEmitterOptions): Promise<any[]>;Creates a
Promise
that is fulfilled when theEventEmitter
emits the given event or that is rejected if theEventEmitter
emits'error'
while waiting. ThePromise
will resolve with an array of all the arguments emitted to the given event.This method is intentionally generic and works with the web platform EventTarget interface, which has no special
'error'
event semantics and does not listen to the'error'
event.import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }
The special handling of the
'error'
event is only used whenevents.once()
is used to wait for another event. Ifevents.once()
is used to wait for the 'error'
event itself, then it is treated as any other kind of event without special handling:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom
An
AbortSignal
can be used to cancel waiting for the event:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled!
- n?: number,): void;
import { setMaxListeners, EventEmitter } from 'node:events'; const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter);
@param nA non-negative number. The maximum number of listeners per
EventTarget
event.@param eventTargetsZero or more {EventTarget} or {EventEmitter} instances. If none are specified,
n
is set as the default max for all newly created {EventTarget} and {EventEmitter} objects. A utility method for creating a web
WritableStream
from aWritable
.
- Extends
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
Synchronous stat(2) - Get file status.
- mode?: number,): void;
Tests a user's permissions for the file or directory specified by
path
. Themode
argument is an optional integer that specifies the accessibility checks to be performed.mode
should be either the valuefs.constants.F_OK
or a mask consisting of the bitwise OR of any offs.constants.R_OK
,fs.constants.W_OK
, andfs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK
). CheckFile access constants
for possible values ofmode
.The final argument,
callback
, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be anError
object. The following examples check ifpackage.json
exists, and if it is readable or writable.import { access, constants } from 'node:fs'; const file = 'package.json'; // Check if the file exists in the current directory. access(file, constants.F_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); }); // Check if the file is readable. access(file, constants.R_OK, (err) => { console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); }); // Check if the file is writable. access(file, constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); }); // Check if the file is readable and writable. access(file, constants.R_OK | constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); });
Do not use
fs.access()
to check for the accessibility of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (!err) { console.error('myfile already exists'); return; } open('myfile', 'wx', (err, fd) => { if (err) throw err; try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); });
write (RECOMMENDED)
import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } });
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } open('myfile', 'r', (err, fd) => { if (err) throw err; try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); });
read (RECOMMENDED)
import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } });
The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The
fs.access()
function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.): void;Asynchronously tests a user's permissions for the file specified by path.
@param pathA path to a file or directory. If a URL is provided, it must use the
file:
protocol. - mode?: number): void;
Synchronously tests a user's permissions for the file or directory specified by
path
. Themode
argument is an optional integer that specifies the accessibility checks to be performed.mode
should be either the valuefs.constants.F_OK
or a mask consisting of the bitwise OR of any offs.constants.R_OK
,fs.constants.W_OK
, andfs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK
). CheckFile access constants
for possible values ofmode
.If any of the accessibility checks fail, an
Error
will be thrown. Otherwise, the method will returnundefined
.import { accessSync, constants } from 'node:fs'; try { accessSync('etc/passwd', constants.R_OK | constants.W_OK); console.log('can read/write'); } catch (err) { console.error('no access!'); }
- ): void;
Asynchronously append data to a file, creating the file if it does not yet exist.
data
can be a string or aBuffer
.The
mode
option only affects the newly created file. See open for more details.import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); });
If
options
is a string, then it specifies the encoding:import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback);
The
path
may be specified as a numeric file descriptor that has been opened for appending (usingfs.open()
orfs.openSync()
). The file descriptor will not be closed automatically.import { open, close, appendFile } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('message.txt', 'a', (err, fd) => { if (err) throw err; try { appendFile(fd, 'data to append', 'utf8', (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); throw err; } });
@param pathfilename or file descriptor
): void;Asynchronously append data to a file, creating the file if it does not exist.
@param fileA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param dataThe data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
- ): void;
Synchronously append data to a file, creating the file if it does not yet exist.
data
can be a string or aBuffer
.The
mode
option only affects the newly created file. See open for more details.import { appendFileSync } from 'node:fs'; try { appendFileSync('message.txt', 'data to append'); console.log('The "data to append" was appended to file!'); } catch (err) { // Handle the error }
If
options
is a string, then it specifies the encoding:import { appendFileSync } from 'node:fs'; appendFileSync('message.txt', 'data to append', 'utf8');
The
path
may be specified as a numeric file descriptor that has been opened for appending (usingfs.open()
orfs.openSync()
). The file descriptor will not be closed automatically.import { openSync, closeSync, appendFileSync } from 'node:fs'; let fd; try { fd = openSync('message.txt', 'a'); appendFileSync(fd, 'data to append', 'utf8'); } catch (err) { // Handle the error } finally { if (fd !== undefined) closeSync(fd); }
@param pathfilename or file descriptor
- ): void;
Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX
chmod(2)
documentation for more detail.import { chmod } from 'node:fs'; chmod('my_file.txt', 0o775, (err) => { if (err) throw err; console.log('The permissions for file "my_file.txt" have been changed!'); });
- uid: number,gid: number,): void;
Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX
chown(2)
documentation for more detail. - fd: number,): void;
Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.
Calling
fs.close()
on any file descriptor (fd
) that is currently in use through any otherfs
operation may lead to undefined behavior.See the POSIX
close(2)
documentation for more detail. - ): void;
Asynchronously copies
src
todest
. By default,dest
is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.mode
is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
).fs.constants.COPYFILE_EXCL
: The copy operation will fail ifdest
already exists.fs.constants.COPYFILE_FICLONE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
@param srcsource filename to copy
@param destdestination filename of the copy operation
mode: number,): void;Asynchronously copies
src
todest
. By default,dest
is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.mode
is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
).fs.constants.COPYFILE_EXCL
: The copy operation will fail ifdest
already exists.fs.constants.COPYFILE_FICLONE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
@param srcsource filename to copy
@param destdestination filename of the copy operation
@param modemodifiers for copy operation.
- mode?: number): void;
Synchronously copies
src
todest
. By default,dest
is overwritten if it already exists. Returnsundefined
. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.mode
is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
).fs.constants.COPYFILE_EXCL
: The copy operation will fail ifdest
already exists.fs.constants.COPYFILE_FICLONE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFileSync, constants } from 'node:fs'; // destination.txt will be created or overwritten by default. copyFileSync('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
@param srcsource filename to copy
@param destdestination filename of the copy operation
@param modemodifiers for copy operation.
- callback: (err: null | ErrnoException) => void): void;
Asynchronously copies the entire directory structure from
src
todest
, including subdirectories and files.When copying a directory to another directory, globs are not supported and behavior is similar to
cp dir1/ dir2/
.callback: (err: null | ErrnoException) => void): void;Asynchronously copies the entire directory structure from
src
todest
, including subdirectories and files.When copying a directory to another directory, globs are not supported and behavior is similar to
cp dir1/ dir2/
. - ): void;
Synchronously copies the entire directory structure from
src
todest
, including subdirectories and files.When copying a directory to another directory, globs are not supported and behavior is similar to
cp dir1/ dir2/
. - options?: BufferEncoding | ReadStreamOptions
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file. Bothstart
andend
are inclusive and start counting at 0, allowed values are in the [0,Number.MAX_SAFE_INTEGER
] range. Iffd
is specified andstart
is omitted orundefined
,fs.createReadStream()
reads sequentially from the current file position. Theencoding
can be any one of those accepted byBuffer
.If
fd
is specified,ReadStream
will ignore thepath
argument and will use the specified file descriptor. This means that no'open'
event will be emitted.fd
should be blocking; non-blockingfd
s should be passed tonet.Socket
.If
fd
points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.By default, the stream will emit a
'close'
event after it has been destroyed. Set theemitClose
option tofalse
to change this behavior.By providing the
fs
option, it is possible to override the correspondingfs
implementations foropen
,read
, andclose
. When providing thefs
option, an override forread
is required. If nofd
is provided, an override foropen
is also required. IfautoClose
istrue
, an override forclose
is also required.import { createReadStream } from 'node:fs'; // Create a stream from some character device. const stream = createReadStream('/dev/input/event0'); setTimeout(() => { stream.close(); // This may not close the stream. // Artificially marking end-of-stream, as if the underlying resource had // indicated end-of-file by itself, allows the stream to close. // This does not cancel pending read operations, and if there is such an // operation, the process may still not be able to exit successfully // until it finishes. stream.push(null); stream.read(0); }, 100);
If
autoClose
is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. IfautoClose
is set to true (default behavior), on'error'
or'end'
the file descriptor will be closed automatically.mode
sets the file mode (permission and sticky bits), but only if the file was created.An example to read the last 10 bytes of a file which is 100 bytes long:
import { createReadStream } from 'node:fs'; createReadStream('sample.txt', { start: 90, end: 99 });
If
options
is a string, then it specifies the encoding. - options?: BufferEncoding | WriteStreamOptions
options
may also include astart
option to allow writing data at some position past the beginning of the file, allowed values are in the [0,Number.MAX_SAFE_INTEGER
] range. Modifying a file rather than replacing it may require theflags
option to be set tor+
rather than the defaultw
. Theencoding
can be any one of those accepted byBuffer
.If
autoClose
is set to true (default behavior) on'error'
or'finish'
the file descriptor will be closed automatically. IfautoClose
is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.By default, the stream will emit a
'close'
event after it has been destroyed. Set theemitClose
option tofalse
to change this behavior.By providing the
fs
option it is possible to override the correspondingfs
implementations foropen
,write
,writev
, andclose
. Overridingwrite()
withoutwritev()
can reduce performance as some optimizations (_writev()
) will be disabled. When providing thefs
option, overrides for at least one ofwrite
andwritev
are required. If nofd
option is supplied, an override foropen
is also required. IfautoClose
istrue
, an override forclose
is also required.Like
fs.ReadStream
, iffd
is specified,fs.WriteStream
will ignore thepath
argument and will use the specified file descriptor. This means that no'open'
event will be emitted.fd
should be blocking; non-blockingfd
s should be passed tonet.Socket
.If
options
is a string, then it specifies the encoding. - fd: number,): void;
Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback.
See the POSIX
fchmod(2)
documentation for more detail. - fd: number,): void;
Sets the permissions on the file. Returns
undefined
.See the POSIX
fchmod(2)
documentation for more detail. - fd: number,uid: number,gid: number,): void;
Sets the owner of the file. No arguments other than a possible exception are given to the completion callback.
See the POSIX
fchown(2)
documentation for more detail. - fd: number,uid: number,gid: number): void;
Sets the owner of the file. Returns
undefined
.See the POSIX
fchown(2)
documentation for more detail.@param uidThe file's new owner's user id.
@param gidThe file's new group's group id.
- fd: number,): void;
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX
fdatasync(2)
documentation for details. No arguments other than a possible exception are given to the completion callback. - fd: number): void;
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX
fdatasync(2)
documentation for details. Returnsundefined
. - fd: number,): void;
Invokes the callback with the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail. - fd: number,
Retrieves the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.fd: number,Retrieves the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.fd: number,Retrieves the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail. - fd: number,): void;
Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX
fsync(2)
documentation for more detail. No arguments other than a possible exception are given to the completion callback. - fd: number,len?: number,): void;
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
See the POSIX
ftruncate(2)
documentation for more detail.If the file referred to by the file descriptor was larger than
len
bytes, only the firstlen
bytes will be retained in the file.For example, the following program retains only the first four bytes of the file:
import { open, close, ftruncate } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('temp.txt', 'r+', (err, fd) => { if (err) throw err; try { ftruncate(fd, 4, (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); if (err) throw err; } });
If the file previously was shorter than
len
bytes, it is extended, and the extended part is filled with null bytes ('\0'
):If
len
is negative then0
will be used.fd: number,): void;Asynchronous ftruncate(2) - Truncate a file to a specified length.
@param fdA file descriptor.
- fd: number,len?: number): void;
Truncates the file descriptor. Returns
undefined
.For detailed information, see the documentation of the asynchronous version of this API: ftruncate.
- fd: number,): void;
Change the file system timestamps of the object referenced by the supplied file descriptor. See utimes.
- fd: number,): void;
Synchronous version of futimes. Returns
undefined
. - pattern: string | string[],callback: (err: null | ErrnoException, matches: string[]) => void): void;
Retrieves the files matching the specified pattern.
pattern: string | string[],): void;Retrieves the files matching the specified pattern.
pattern: string | string[],callback: (err: null | ErrnoException, matches: string[]) => void): void;Retrieves the files matching the specified pattern.
pattern: string | string[],): void;Retrieves the files matching the specified pattern.
- pattern: string | string[]): string[];
Retrieves the files matching the specified pattern.
pattern: string | string[],Retrieves the files matching the specified pattern.
pattern: string | string[],): string[];Retrieves the files matching the specified pattern.
pattern: string | string[],Retrieves the files matching the specified pattern.
- uid: number,gid: number,): void;
Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback.
See the POSIX
lchown(2)
documentation for more detail. - uid: number,gid: number): void;
Set the owner for the path. Returns
undefined
.See the POSIX
lchown(2)
documentation for more details.@param uidThe file's new owner's user id.
@param gidThe file's new group's group id.
- ): void;
Creates a new link from the
existingPath
to thenewPath
. See the POSIXlink(2)
documentation for more detail. No arguments other than a possible exception are given to the completion callback. - ): void;
Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.): void;Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.): void;Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.): void;Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details. - ): void;
Changes the access and modification times of a file in the same way as utimes, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.
No arguments other than a possible exception are given to the completion callback.
- ): void;
Change the file system timestamps of the symbolic link referenced by
path
. Returnsundefined
, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of lutimes. - callback: (err: null | ErrnoException, path?: string) => void): void;
Asynchronously creates a directory.
The callback is given a possible exception and, if
recursive
istrue
, the first directory path created,(err[, path])
.path
can still beundefined
whenrecursive
istrue
, if no directory was created (for instance, if it was previously created).The optional
options
argument can be an integer specifyingmode
(permission and sticky bits), or an object with amode
property and arecursive
property indicating whether parent directories should be created. Callingfs.mkdir()
whenpath
is a directory that exists results in an error only whenrecursive
is false. Ifrecursive
is false and the directory exists, anEEXIST
error occurs.import { mkdir } from 'node:fs'; // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. mkdir('./tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; });
On Windows, using
fs.mkdir()
on the root directory even with recursion will result in an error:import { mkdir } from 'node:fs'; mkdir('/', { recursive: true }, (err) => { // => [Error: EPERM: operation not permitted, mkdir 'C:\'] });
See the POSIX
mkdir(2)
documentation for more details.): void;Asynchronous mkdir(2) - create a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsEither the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to
0o777
.callback: (err: null | ErrnoException, path?: string) => void): void;Asynchronous mkdir(2) - create a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsEither the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to
0o777
.): void;Asynchronous mkdir(2) - create a directory with a mode of
0o777
.@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. - ): undefined | string;
Synchronously creates a directory. Returns
undefined
, or ifrecursive
istrue
, the first directory path created. This is the synchronous version of mkdir.See the POSIX
mkdir(2)
documentation for more details.): void;Synchronous mkdir(2) - create a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsEither the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to
0o777
.): undefined | string;Synchronous mkdir(2) - create a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsEither the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to
0o777
. - prefix: string,callback: (err: null | ErrnoException, folder: string) => void): void;
Creates a unique temporary directory.
Generates six random characters to be appended behind a required
prefix
to create a unique temporary directory. Due to platform inconsistencies, avoid trailingX
characters inprefix
. Some platforms, notably the BSDs, can return more than six random characters, and replace trailingX
characters inprefix
with random characters.The created directory path is passed as a string to the callback's second parameter.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use.import { mkdtemp } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { if (err) throw err; console.log(directory); // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 });
The
fs.mkdtemp()
method will append the six randomly selected characters directly to theprefix
string. For instance, given a directory/tmp
, if the intention is to create a temporary directory within/tmp
, theprefix
must end with a trailing platform-specific path separator (import { sep } from 'node:path'
).import { tmpdir } from 'node:os'; import { mkdtemp } from 'node:fs'; // The parent directory for the new temporary directory const tmpDir = tmpdir(); // This method is *INCORRECT*: mkdtemp(tmpDir, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmpabc123`. // A new temporary directory is created at the file system root // rather than *within* the /tmp directory. }); // This method is *CORRECT*: import { sep } from 'node:path'; mkdtemp(`${tmpDir}${sep}`, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmp/abc123`. // A new temporary directory is created within // the /tmp directory. });
prefix: string,options: 'buffer' | { encoding: 'buffer' },): void;Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.prefix: string,): void;Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.prefix: string,callback: (err: null | ErrnoException, folder: string) => void): void;Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
- prefix: string,): string;
Returns the created directory path.
For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use.prefix: string,Synchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.prefix: string,Synchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used. - callback: (err: null | ErrnoException, fd: number) => void): void;
Asynchronous file open. See the POSIX
open(2)
documentation for more details.mode
sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see chmod.The callback gets two arguments
(err, fd)
.Some characters (
< > : " / \ | ? *
) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.Functions based on
fs.open()
exhibit this behavior as well:fs.writeFile()
,fs.readFile()
, etc.@param flagsSee
support of file system
flags``.callback: (err: null | ErrnoException, fd: number) => void): void;Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be
0o666
.@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param flagsSee
support of file system
flags``. Returns a
Blob
whose data is backed by the given file.The file must not be modified after the
Blob
is created. Any modifications will cause reading theBlob
data to fail with aDOMException
error. Synchronous stat operations on the file when theBlob
is created, and before each read in order to detect whether the file data has been modified on disk.import { openAsBlob } from 'node:fs'; const blob = await openAsBlob('the.file.txt'); const ab = await blob.arrayBuffer(); blob.stream();
- ): void;
Asynchronously open a directory. See the POSIX
opendir(3)
documentation for more details.Creates an
fs.Dir
, which contains all further functions for reading from and cleaning up the directory.The
encoding
option sets the encoding for thepath
while opening the directory and subsequent read operations.): void;Asynchronously open a directory. See the POSIX
opendir(3)
documentation for more details.Creates an
fs.Dir
, which contains all further functions for reading from and cleaning up the directory.The
encoding
option sets the encoding for thepath
while opening the directory and subsequent read operations. Synchronously open a directory. See
opendir(3)
.Creates an
fs.Dir
, which contains all further functions for reading from and cleaning up the directory.The
encoding
option sets the encoding for thepath
while opening the directory and subsequent read operations.- fd: number,buffer: TBuffer,offset: number,length: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;
Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.@param bufferThe buffer that the data will be written to.
@param offsetThe position in
buffer
to write the data to.@param lengthThe number of bytes to read.
@param positionSpecifies where to begin reading from in the file. If
position
isnull
or-1
, data will be read from the current file position, and the file position will be updated. Ifposition
is an integer, the file position will be unchanged.fd: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;Similar to the above
fs.read
function, this version takes an optionaloptions
object. If not otherwise specified in anoptions
object,buffer
defaults toBuffer.alloc(16384)
,offset
defaults to0
,length
defaults tobuffer.byteLength
,- offset
as of Node 17.6.0position
defaults tonull
fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.@param bufferThe buffer that the data will be written to.
fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.@param bufferThe buffer that the data will be written to.
fd: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: ArrayBufferView) => void): void;Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties. - options: undefined | null | BufferEncoding | { encoding: unknown; recursive: boolean; withFileTypes: false },callback: (err: null | ErrnoException, files: string[]) => void): void;
Reads the contents of a directory. The callback gets two arguments
(err, files)
wherefiles
is an array of the names of the files in the directory excluding'.'
and'..'
.See the POSIX
readdir(3)
documentation for more details.The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the filenames passed to the callback. If theencoding
is set to'buffer'
, the filenames returned will be passed asBuffer
objects.If
options.withFileTypes
is set totrue
, thefiles
array will containfs.Dirent
objects.options: 'buffer' | { encoding: 'buffer'; recursive: boolean; withFileTypes: false },): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.options: undefined | null | BufferEncoding | ObjectEncodingOptions & { recursive: boolean; withFileTypes: false },): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.callback: (err: null | ErrnoException, files: string[]) => void): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsIf called with
withFileTypes: true
the result data will be an array of Dirent. - options?: null | BufferEncoding | { encoding: unknown; recursive: boolean; withFileTypes: false }): string[];
Reads the contents of the directory.
See the POSIX
readdir(3)
documentation for more details.The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the filenames returned. If theencoding
is set to'buffer'
, the filenames returned will be passed asBuffer
objects.If
options.withFileTypes
is set totrue
, the result will containfs.Dirent
objects.options: 'buffer' | { encoding: 'buffer'; recursive: boolean; withFileTypes: false }Synchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.options?: null | BufferEncoding | ObjectEncodingOptions & { recursive: boolean; withFileTypes: false }Synchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.Synchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsIf called with
withFileTypes: true
the result data will be an array of Dirent. - ): void;
Asynchronously reads the entire contents of a file.
import { readFile } from 'node:fs'; readFile('/etc/passwd', (err, data) => { if (err) throw err; console.log(data); });
The callback is passed two arguments
(err, data)
, wheredata
is the contents of the file.If no encoding is specified, then the raw buffer is returned.
If
options
is a string, then it specifies the encoding:import { readFile } from 'node:fs'; readFile('/etc/passwd', 'utf8', callback);
When the path is a directory, the behavior of
fs.readFile()
and readFileSync is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.import { readFile } from 'node:fs'; // macOS, Linux, and Windows readFile('<directory>', (err, data) => { // => [Error: EISDIR: illegal operation on a directory, read <directory>] }); // FreeBSD readFile('<directory>', (err, data) => { // => null, <data> });
It is possible to abort an ongoing request using an
AbortSignal
. If a request is aborted the callback is called with anAbortError
:import { readFile } from 'node:fs'; const controller = new AbortController(); const signal = controller.signal; readFile(fileInfo[0].name, { signal }, (err, buf) => { // ... }); // When you want to abort the request controller.abort();
The
fs.readFile()
function buffers the entire file. To minimize memory costs, when possible prefer streaming viafs.createReadStream()
.Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering
fs.readFile
performs.@param pathfilename or file descriptor
callback: (err: null | ErrnoException, data: string) => void): void;Asynchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param optionsEither the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to
'r'
.): void;Asynchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param optionsEither the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to
'r'
.): void;Asynchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically. - options?: null | { encoding: null; flag: string }
Returns the contents of the
path
.For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the
encoding
option is specified then this function returns a string. Otherwise it returns a buffer.Similar to readFile, when the path is a directory, the behavior of
fs.readFileSync()
is platform-specific.import { readFileSync } from 'node:fs'; // macOS, Linux, and Windows readFileSync('<directory>'); // => [Error: EISDIR: illegal operation on a directory, read <directory>] // FreeBSD readFileSync('<directory>'); // => <data>
@param pathfilename or file descriptor
options: BufferEncoding | { encoding: BufferEncoding; flag: string }): string;Synchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param optionsEither the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to
'r'
.Synchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param optionsEither the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to
'r'
. - callback: (err: null | ErrnoException, linkString: string) => void): void;
Reads the contents of the symbolic link referred to by
path
. The callback gets two arguments(err, linkString)
.See the POSIX
readlink(2)
documentation for more details.The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the link path passed to the callback. If theencoding
is set to'buffer'
, the link path returned will be passed as aBuffer
object.): void;Asynchronous readlink(2) - read value of a symbolic link.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.): void;Asynchronous readlink(2) - read value of a symbolic link.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used. - ): string;
Returns the symbolic link's string value.
See the POSIX
readlink(2)
documentation for more details.The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the link path returned. If theencoding
is set to'buffer'
, the link path returned will be passed as aBuffer
object.Synchronous readlink(2) - read value of a symbolic link.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.Synchronous readlink(2) - read value of a symbolic link.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used. - fd: number,buffer: ArrayBufferView,offset: number,length: number,): number;
Returns the number of
bytesRead
.For detailed information, see the documentation of the asynchronous version of this API: read.
fd: number,buffer: ArrayBufferView,): number;Similar to the above
fs.readSync
function, this version takes an optionaloptions
object. If nooptions
object is specified, it will default with the above values. - fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],cb: (err: null | ErrnoException, bytesRead: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;
Read from a file specified by
fd
and write to an array ofArrayBufferView
s usingreadv()
.position
is the offset from the beginning of the file from where data should be read. Iftypeof position !== 'number'
, the data will be read from the current position.The callback will be given three arguments:
err
,bytesRead
, andbuffers
.bytesRead
is how many bytes were read from the file.If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffers
properties.fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],position: null | number,cb: (err: null | ErrnoException, bytesRead: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;Read from a file specified by
fd
and write to an array ofArrayBufferView
s usingreadv()
.position
is the offset from the beginning of the file from where data should be read. Iftypeof position !== 'number'
, the data will be read from the current position.The callback will be given three arguments:
err
,bytesRead
, andbuffers
.bytesRead
is how many bytes were read from the file.If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffers
properties. - fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],position?: number): number;
For detailed information, see the documentation of the asynchronous version of this API: readv.
@returnsThe number of bytes read.
- callback: (err: null | ErrnoException, resolvedPath: string) => void): void;
Asynchronously computes the canonical pathname by resolving
.
,..
, and symbolic links.A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.
This function behaves like
realpath(3)
, with some exceptions:- No case conversion is performed on case-insensitive file systems.
- The maximum number of symbolic links is platform-independent and generally (much) higher than what the native
realpath(3)
implementation supports.
The
callback
gets two arguments(err, resolvedPath)
. May useprocess.cwd
to resolve relative paths.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.If
path
resolves to a socket or a pipe, the function will return a system dependent name for that object.): void;Asynchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.): void;Asynchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.callback: (err: null | ErrnoException, resolvedPath: string) => void): void;Asynchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.callback: (err: null | ErrnoException, resolvedPath: string) => void): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: string) => void): void;Asynchronous
realpath(3)
.The
callback
gets two arguments(err, resolvedPath)
.Only paths that can be converted to UTF8 strings are supported.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the path passed to the callback. If theencoding
is set to'buffer'
, the path returned will be passed as aBuffer
object.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/proc
in order for this function to work. Glibc does not have this restriction. - ): string;
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of this API: realpath.
Synchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.Synchronous realpath(3) - return the canonicalized absolute pathname.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used. - ): void;
Asynchronously rename file at
oldPath
to the pathname provided asnewPath
. In the case thatnewPath
already exists, it will be overwritten. If there is a directory atnewPath
, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.See also:
rename(2)
.import { rename } from 'node:fs'; rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; console.log('Rename complete!'); });
- ): void;
Renames the file from
oldPath
tonewPath
. Returnsundefined
.See the POSIX
rename(2)
documentation for more details. - ): void;
Asynchronously removes files and directories (modeled on the standard POSIX
rm
utility). No arguments other than a possible exception are given to the completion callback.): void;Asynchronously removes files and directories (modeled on the standard POSIX
rm
utility). No arguments other than a possible exception are given to the completion callback. - ): void;
Asynchronous
rmdir(2)
. No arguments other than a possible exception are given to the completion callback.Using
fs.rmdir()
on a file (not a directory) results in anENOENT
error on Windows and anENOTDIR
error on POSIX.To get a behavior similar to the
rm -rf
Unix command, use rm with options{ recursive: true, force: true }
.): void;Asynchronous
rmdir(2)
. No arguments other than a possible exception are given to the completion callback.Using
fs.rmdir()
on a file (not a directory) results in anENOENT
error on Windows and anENOTDIR
error on POSIX.To get a behavior similar to the
rm -rf
Unix command, use rm with options{ recursive: true, force: true }
. - ): void;
Synchronous
rmdir(2)
. Returnsundefined
.Using
fs.rmdirSync()
on a file (not a directory) results in anENOENT
error on Windows and anENOTDIR
error on POSIX.To get a behavior similar to the
rm -rf
Unix command, use rmSync with options{ recursive: true, force: true }
. - ): void;
Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
): void;Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
): void;Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
): void;Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
- ): void;
Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
): void;Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
): void;Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
): void;Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
Synchronous
statfs(2)
. Returns information about the mounted file system which containspath
.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
Synchronous
statfs(2)
. Returns information about the mounted file system which containspath
.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
Synchronous
statfs(2)
. Returns information about the mounted file system which containspath
.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
- ): void;
Creates the link called
path
pointing totarget
. No arguments other than a possible exception are given to the completion callback.See the POSIX
symlink(2)
documentation for more details.The
type
argument is only available on Windows and ignored on other platforms. It can be set to'dir'
,'file'
, or'junction'
. If thetype
argument is not a string, Node.js will autodetecttarget
type and use'file'
or'dir'
. If thetarget
does not exist,'file'
will be used. Windows junction points require the destination path to be absolute. When using'junction'
, thetarget
argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs'; symlink('./mew', './mewtwo', callback);
The above example creates a symbolic link
mewtwo
which points tomew
in the same directory:tree .
. ├── mew └── mewtwo -> ./mew
): void;Asynchronous symlink(2) - Create a new symbolic link to an existing file.
@param targetA path to an existing file. If a URL is provided, it must use the
file:
protocol.@param pathA path to the new symlink. If a URL is provided, it must use the
file:
protocol.type Type = 'dir' | 'file' | 'junction' - ): void;
Returns
undefined
.For detailed information, see the documentation of the asynchronous version of this API: symlink.
- ): void;
Asynchronous truncate(2) - Truncate a file to a specified length.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. - ): void;
Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
import { unlink } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. unlink('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was deleted'); });
fs.unlink()
will not work on a directory, empty or otherwise. To remove a directory, use rmdir.See the POSIX
unlink(2)
documentation for more details. - ): void;
Stop watching for changes on
filename
. Iflistener
is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching offilename
.Calling
fs.unwatchFile()
with a filename that is not being watched is a no-op, not an error.Using watch is more efficient than
fs.watchFile()
andfs.unwatchFile()
.fs.watch()
should be used instead offs.watchFile()
andfs.unwatchFile()
when possible.@param listenerOptional, a listener previously attached using
fs.watchFile()
): void;Stop watching for changes on
filename
. Iflistener
is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching offilename
.Calling
fs.unwatchFile()
with a filename that is not being watched is a no-op, not an error.Using watch is more efficient than
fs.watchFile()
andfs.unwatchFile()
.fs.watch()
should be used instead offs.watchFile()
andfs.unwatchFile()
when possible.@param listenerOptional, a listener previously attached using
fs.watchFile()
- ): void;
Change the file system timestamps of the object referenced by
path
.The
atime
andmtime
arguments follow these rules:- Values can be either numbers representing Unix epoch time in seconds,
Date
s, or a numeric string like'123456789.0'
. - If the value can not be converted to a number, or is
NaN
,Infinity
, or-Infinity
, anError
will be thrown.
- Values can be either numbers representing Unix epoch time in seconds,
- ): void;
Returns
undefined
.For detailed information, see the documentation of the asynchronous version of this API: utimes.
Watch for changes on
filename
, wherefilename
is either a file or a directory.The second argument is optional. If
options
is provided as a string, it specifies theencoding
. Otherwiseoptions
should be passed as an object.The listener callback gets two arguments
(eventType, filename)
.eventType
is either'rename'
or'change'
, andfilename
is the name of the file which triggered the event.On most platforms,
'rename'
is emitted whenever a filename appears or disappears in the directory.The listener callback is attached to the
'change'
event fired byfs.FSWatcher
, but it is not the same thing as the'change'
value ofeventType
.If a
signal
is passed, aborting the corresponding AbortController will close the returnedfs.FSWatcher
.Watch for changes on
filename
, wherefilename
is either a file or a directory, returning anFSWatcher
.@param filenameA path to a file or directory. If a URL is provided, it must use the
file:
protocol.@param optionsEither the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. If
encoding
is not supplied, the default of'utf8'
is used. Ifpersistent
is not supplied, the default oftrue
is used. Ifrecursive
is not supplied, the default offalse
is used.Watch for changes on
filename
, wherefilename
is either a file or a directory, returning anFSWatcher
.@param filenameA path to a file or directory. If a URL is provided, it must use the
file:
protocol.@param optionsEither the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. If
encoding
is not supplied, the default of'utf8'
is used. Ifpersistent
is not supplied, the default oftrue
is used. Ifrecursive
is not supplied, the default offalse
is used.Watch for changes on
filename
, wherefilename
is either a file or a directory, returning anFSWatcher
.@param filenameA path to a file or directory. If a URL is provided, it must use the
file:
protocol.Watch for changes on
filename
. The callbacklistener
will be called each time the file is accessed.The
options
argument may be omitted. If provided, it should be an object. Theoptions
object may contain a boolean namedpersistent
that indicates whether the process should continue to run as long as files are being watched. Theoptions
object may specify aninterval
property indicating how often the target should be polled in milliseconds.The
listener
gets two arguments the current stat object and the previous stat object:import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); });
These stat objects are instances of
fs.Stat
. If thebigint
option istrue
, the numeric values in these objects are specified asBigInt
s.To be notified when the file was modified, not just accessed, it is necessary to compare
curr.mtimeMs
andprev.mtimeMs
.When an
fs.watchFile
operation results in anENOENT
error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.Using watch is more efficient than
fs.watchFile
andfs.unwatchFile
.fs.watch
should be used instead offs.watchFile
andfs.unwatchFile
when possible.When a file being watched by
fs.watchFile()
disappears and reappears, then the contents ofprevious
in the second callback event (the file's reappearance) will be the same as the contents ofprevious
in the first callback event (its disappearance).This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name
Watch for changes on
filename
. The callbacklistener
will be called each time the file is accessed.The
options
argument may be omitted. If provided, it should be an object. Theoptions
object may contain a boolean namedpersistent
that indicates whether the process should continue to run as long as files are being watched. Theoptions
object may specify aninterval
property indicating how often the target should be polled in milliseconds.The
listener
gets two arguments the current stat object and the previous stat object:import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); });
These stat objects are instances of
fs.Stat
. If thebigint
option istrue
, the numeric values in these objects are specified asBigInt
s.To be notified when the file was modified, not just accessed, it is necessary to compare
curr.mtimeMs
andprev.mtimeMs
.When an
fs.watchFile
operation results in anENOENT
error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.Using watch is more efficient than
fs.watchFile
andfs.unwatchFile
.fs.watch
should be used instead offs.watchFile
andfs.unwatchFile
when possible.When a file being watched by
fs.watchFile()
disappears and reappears, then the contents ofprevious
in the second callback event (the file's reappearance) will be the same as the contents ofprevious
in the first callback event (its disappearance).This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name
Watch for changes on
filename
. The callbacklistener
will be called each time the file is accessed.@param filenameA path to a file or directory. If a URL is provided, it must use the
file:
protocol.- fd: number,buffer: TBuffer,offset?: null | number,length?: null | number,position?: null | number,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;
Write
buffer
to the file specified byfd
.offset
determines the part of the buffer to be written, andlength
is an integer specifying the number of bytes to write.position
refers to the offset from the beginning of the file where this data should be written. Iftypeof position !== 'number'
, the data will be written at the current position. Seepwrite(2)
.The callback will be given three arguments
(err, bytesWritten, buffer)
wherebytesWritten
specifies how many bytes were written frombuffer
.If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesWritten
andbuffer
properties.It is unsafe to use
fs.write()
multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
fd: number,buffer: TBuffer,offset: undefined | null | number,length: undefined | null | number,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
buffer
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param offsetThe part of the buffer to be written. If not supplied, defaults to
0
.@param lengthThe number of bytes to write. If not supplied, defaults to
buffer.length - offset
.fd: number,buffer: TBuffer,offset: undefined | null | number,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
buffer
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param offsetThe part of the buffer to be written. If not supplied, defaults to
0
.fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
buffer
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
fd: number,string: string,position: undefined | null | number,encoding: undefined | null | BufferEncoding,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
string
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
@param positionThe offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
@param encodingThe expected string encoding.
fd: number,string: string,position: undefined | null | number,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
string
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
@param positionThe offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
fd: number,string: string,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
string
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
- data: string | ArrayBufferView<ArrayBufferLike>,): void;
When
file
is a filename, asynchronously writes data to the file, replacing the file if it already exists.data
can be a string or a buffer.When
file
is a file descriptor, the behavior is similar to callingfs.write()
directly (which is recommended). See the notes below on using a file descriptor.The
encoding
option is ignored ifdata
is a buffer.The
mode
option only affects the newly created file. See open for more details.import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, (err) => { if (err) throw err; console.log('The file has been saved!'); });
If
options
is a string, then it specifies the encoding:import { writeFile } from 'node:fs'; writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
It is unsafe to use
fs.writeFile()
multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.Similarly to
fs.readFile
-fs.writeFile
is a convenience method that performs multiplewrite
calls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.It is possible to use an
AbortSignal
to cancel anfs.writeFile()
. Cancelation is "best effort", and some amount of data is likely still to be written.import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const controller = new AbortController(); const { signal } = controller; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, { signal }, (err) => { // When a request is aborted - the callback is called with an AbortError }); // When the request should be aborted controller.abort();
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering
fs.writeFile
performs.@param filefilename or file descriptor
data: string | ArrayBufferView<ArrayBufferLike>,): void;Asynchronously writes data to a file, replacing the file if it already exists.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param dataThe data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
- data: string | ArrayBufferView<ArrayBufferLike>,): void;
Returns
undefined
.The
mode
option only affects the newly created file. See open for more details.For detailed information, see the documentation of the asynchronous version of this API: writeFile.
@param filefilename or file descriptor
- fd: number,buffer: ArrayBufferView,offset?: null | number,length?: null | number,position?: null | number): number;
For detailed information, see the documentation of the asynchronous version of this API: write.
@returnsThe number of bytes written.
fd: number,string: string,position?: null | number,encoding?: null | BufferEncoding): number;Synchronously writes
string
to the file referenced by the supplied file descriptor, returning the number of bytes written.@param fdA file descriptor.
@param stringA string to write.
@param positionThe offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
@param encodingThe expected string encoding.
- fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],cb: (err: null | ErrnoException, bytesWritten: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;
Write an array of
ArrayBufferView
s to the file specified byfd
usingwritev()
.position
is the offset from the beginning of the file where this data should be written. Iftypeof position !== 'number'
, the data will be written at the current position.The callback will be given three arguments:
err
,bytesWritten
, andbuffers
.bytesWritten
is how many bytes were written frombuffers
.If this method is
util.promisify()
ed, it returns a promise for anObject
withbytesWritten
andbuffers
properties.It is unsafe to use
fs.writev()
multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],position: null | number,cb: (err: null | ErrnoException, bytesWritten: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;Write an array of
ArrayBufferView
s to the file specified byfd
usingwritev()
.position
is the offset from the beginning of the file where this data should be written. Iftypeof position !== 'number'
, the data will be written at the current position.The callback will be given three arguments:
err
,bytesWritten
, andbuffers
.bytesWritten
is how many bytes were written frombuffers
.If this method is
util.promisify()
ed, it returns a promise for anObject
withbytesWritten
andbuffers
properties.It is unsafe to use
fs.writev()
multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
- fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],position?: number): number;
For detailed information, see the documentation of the asynchronous version of this API: writev.
@returnsThe number of bytes written.
Type definitions
- mode?: number,): void;
Tests a user's permissions for the file or directory specified by
path
. Themode
argument is an optional integer that specifies the accessibility checks to be performed.mode
should be either the valuefs.constants.F_OK
or a mask consisting of the bitwise OR of any offs.constants.R_OK
,fs.constants.W_OK
, andfs.constants.X_OK
(e.g.fs.constants.W_OK | fs.constants.R_OK
). CheckFile access constants
for possible values ofmode
.The final argument,
callback
, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be anError
object. The following examples check ifpackage.json
exists, and if it is readable or writable.import { access, constants } from 'node:fs'; const file = 'package.json'; // Check if the file exists in the current directory. access(file, constants.F_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); }); // Check if the file is readable. access(file, constants.R_OK, (err) => { console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); }); // Check if the file is writable. access(file, constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); }); // Check if the file is readable and writable. access(file, constants.R_OK | constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); });
Do not use
fs.access()
to check for the accessibility of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (!err) { console.error('myfile already exists'); return; } open('myfile', 'wx', (err, fd) => { if (err) throw err; try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); });
write (RECOMMENDED)
import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } try { writeMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } });
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } open('myfile', 'r', (err, fd) => { if (err) throw err; try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } }); });
read (RECOMMENDED)
import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } try { readMyData(fd); } finally { close(fd, (err) => { if (err) throw err; }); } });
The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The
fs.access()
function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.): void;Asynchronously tests a user's permissions for the file specified by path.
@param pathA path to a file or directory. If a URL is provided, it must use the
file:
protocol.namespace access
- ): void;
Asynchronously append data to a file, creating the file if it does not yet exist.
data
can be a string or aBuffer
.The
mode
option only affects the newly created file. See open for more details.import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); });
If
options
is a string, then it specifies the encoding:import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback);
The
path
may be specified as a numeric file descriptor that has been opened for appending (usingfs.open()
orfs.openSync()
). The file descriptor will not be closed automatically.import { open, close, appendFile } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('message.txt', 'a', (err, fd) => { if (err) throw err; try { appendFile(fd, 'data to append', 'utf8', (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); throw err; } });
@param pathfilename or file descriptor
): void;Asynchronously append data to a file, creating the file if it does not exist.
@param fileA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param dataThe data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
namespace appendFile
- ): void;
Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX
chmod(2)
documentation for more detail.import { chmod } from 'node:fs'; chmod('my_file.txt', 0o775, (err) => { if (err) throw err; console.log('The permissions for file "my_file.txt" have been changed!'); });
namespace chmod
- fd: number,): void;
Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.
Calling
fs.close()
on any file descriptor (fd
) that is currently in use through any otherfs
operation may lead to undefined behavior.See the POSIX
close(2)
documentation for more detail.namespace close
- ): void;
Asynchronously copies
src
todest
. By default,dest
is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.mode
is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
).fs.constants.COPYFILE_EXCL
: The copy operation will fail ifdest
already exists.fs.constants.COPYFILE_FICLONE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
@param srcsource filename to copy
@param destdestination filename of the copy operation
mode: number,): void;Asynchronously copies
src
todest
. By default,dest
is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.mode
is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
).fs.constants.COPYFILE_EXCL
: The copy operation will fail ifdest
already exists.fs.constants.COPYFILE_FICLONE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE
: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
@param srcsource filename to copy
@param destdestination filename of the copy operation
@param modemodifiers for copy operation.
namespace copyFile
- fd: number,): void;
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX
fdatasync(2)
documentation for details. No arguments other than a possible exception are given to the completion callback.namespace fdatasync
- fd: number,): void;
Invokes the callback with the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Stats
for the file descriptor.See the POSIX
fstat(2)
documentation for more detail.namespace fstat
- fd: number,): void;
Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX
fsync(2)
documentation for more detail. No arguments other than a possible exception are given to the completion callback.namespace fsync
- fd: number,len?: number,): void;
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
See the POSIX
ftruncate(2)
documentation for more detail.If the file referred to by the file descriptor was larger than
len
bytes, only the firstlen
bytes will be retained in the file.For example, the following program retains only the first four bytes of the file:
import { open, close, ftruncate } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { if (err) throw err; }); } open('temp.txt', 'r+', (err, fd) => { if (err) throw err; try { ftruncate(fd, 4, (err) => { closeFd(fd); if (err) throw err; }); } catch (err) { closeFd(fd); if (err) throw err; } });
If the file previously was shorter than
len
bytes, it is extended, and the extended part is filled with null bytes ('\0'
):If
len
is negative then0
will be used.fd: number,): void;Asynchronous ftruncate(2) - Truncate a file to a specified length.
@param fdA file descriptor.
namespace ftruncate
- fd: number,): void;
Change the file system timestamps of the object referenced by the supplied file descriptor. See utimes.
namespace futimes
- ): void;
Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.): void;Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.): void;Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.): void;Retrieves the
fs.Stats
for the symbolic link referred to by the path. The callback gets two arguments(err, stats)
wherestats
is afs.Stats
object.lstat()
is identical tostat()
, except that ifpath
is a symbolic link, then the link itself is stat-ed, not the file that it refers to.See the POSIX
lstat(2)
documentation for more details.namespace lstat
- ): void;
Changes the access and modification times of a file in the same way as utimes, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.
No arguments other than a possible exception are given to the completion callback.
namespace lutimes
- callback: (err: null | ErrnoException, path?: string) => void): void;
Asynchronously creates a directory.
The callback is given a possible exception and, if
recursive
istrue
, the first directory path created,(err[, path])
.path
can still beundefined
whenrecursive
istrue
, if no directory was created (for instance, if it was previously created).The optional
options
argument can be an integer specifyingmode
(permission and sticky bits), or an object with amode
property and arecursive
property indicating whether parent directories should be created. Callingfs.mkdir()
whenpath
is a directory that exists results in an error only whenrecursive
is false. Ifrecursive
is false and the directory exists, anEEXIST
error occurs.import { mkdir } from 'node:fs'; // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. mkdir('./tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; });
On Windows, using
fs.mkdir()
on the root directory even with recursion will result in an error:import { mkdir } from 'node:fs'; mkdir('/', { recursive: true }, (err) => { // => [Error: EPERM: operation not permitted, mkdir 'C:\'] });
See the POSIX
mkdir(2)
documentation for more details.): void;Asynchronous mkdir(2) - create a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsEither the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to
0o777
.callback: (err: null | ErrnoException, path?: string) => void): void;Asynchronous mkdir(2) - create a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsEither the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to
0o777
.): void;Asynchronous mkdir(2) - create a directory with a mode of
0o777
.@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.namespace mkdir
- prefix: string,callback: (err: null | ErrnoException, folder: string) => void): void;
Creates a unique temporary directory.
Generates six random characters to be appended behind a required
prefix
to create a unique temporary directory. Due to platform inconsistencies, avoid trailingX
characters inprefix
. Some platforms, notably the BSDs, can return more than six random characters, and replace trailingX
characters inprefix
with random characters.The created directory path is passed as a string to the callback's second parameter.
The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use.import { mkdtemp } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { if (err) throw err; console.log(directory); // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 });
The
fs.mkdtemp()
method will append the six randomly selected characters directly to theprefix
string. For instance, given a directory/tmp
, if the intention is to create a temporary directory within/tmp
, theprefix
must end with a trailing platform-specific path separator (import { sep } from 'node:path'
).import { tmpdir } from 'node:os'; import { mkdtemp } from 'node:fs'; // The parent directory for the new temporary directory const tmpDir = tmpdir(); // This method is *INCORRECT*: mkdtemp(tmpDir, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmpabc123`. // A new temporary directory is created at the file system root // rather than *within* the /tmp directory. }); // This method is *CORRECT*: import { sep } from 'node:path'; mkdtemp(`${tmpDir}${sep}`, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmp/abc123`. // A new temporary directory is created within // the /tmp directory. });
prefix: string,options: 'buffer' | { encoding: 'buffer' },): void;Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.prefix: string,): void;Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.prefix: string,callback: (err: null | ErrnoException, folder: string) => void): void;Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
namespace mkdtemp
- callback: (err: null | ErrnoException, fd: number) => void): void;
Asynchronous file open. See the POSIX
open(2)
documentation for more details.mode
sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see chmod.The callback gets two arguments
(err, fd)
.Some characters (
< > : " / \ | ? *
) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.Functions based on
fs.open()
exhibit this behavior as well:fs.writeFile()
,fs.readFile()
, etc.@param flagsSee
support of file system
flags``.callback: (err: null | ErrnoException, fd: number) => void): void;Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be
0o666
.@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param flagsSee
support of file system
flags``.namespace open
- ): void;
Asynchronously open a directory. See the POSIX
opendir(3)
documentation for more details.Creates an
fs.Dir
, which contains all further functions for reading from and cleaning up the directory.The
encoding
option sets the encoding for thepath
while opening the directory and subsequent read operations.): void;Asynchronously open a directory. See the POSIX
opendir(3)
documentation for more details.Creates an
fs.Dir
, which contains all further functions for reading from and cleaning up the directory.The
encoding
option sets the encoding for thepath
while opening the directory and subsequent read operations.namespace opendir
- fd: number,buffer: TBuffer,offset: number,length: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;
Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.@param bufferThe buffer that the data will be written to.
@param offsetThe position in
buffer
to write the data to.@param lengthThe number of bytes to read.
@param positionSpecifies where to begin reading from in the file. If
position
isnull
or-1
, data will be read from the current file position, and the file position will be updated. Ifposition
is an integer, the file position will be unchanged.fd: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;Similar to the above
fs.read
function, this version takes an optionaloptions
object. If not otherwise specified in anoptions
object,buffer
defaults toBuffer.alloc(16384)
,offset
defaults to0
,length
defaults tobuffer.byteLength
,- offset
as of Node 17.6.0position
defaults tonull
fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.@param bufferThe buffer that the data will be written to.
fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, bytesRead: number, buffer: TBuffer) => void): void;Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.@param bufferThe buffer that the data will be written to.
fd: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: ArrayBufferView) => void): void;Read data from the file specified by
fd
.The callback is given the three arguments,
(err, bytesRead, buffer)
.If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffer
properties.namespace read
- options: undefined | null | BufferEncoding | { encoding: unknown; recursive: boolean; withFileTypes: false },callback: (err: null | ErrnoException, files: string[]) => void): void;
Reads the contents of a directory. The callback gets two arguments
(err, files)
wherefiles
is an array of the names of the files in the directory excluding'.'
and'..'
.See the POSIX
readdir(3)
documentation for more details.The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the filenames passed to the callback. If theencoding
is set to'buffer'
, the filenames returned will be passed asBuffer
objects.If
options.withFileTypes
is set totrue
, thefiles
array will containfs.Dirent
objects.options: 'buffer' | { encoding: 'buffer'; recursive: boolean; withFileTypes: false },): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.options: undefined | null | BufferEncoding | ObjectEncodingOptions & { recursive: boolean; withFileTypes: false },): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.callback: (err: null | ErrnoException, files: string[]) => void): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.): void;Asynchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsIf called with
withFileTypes: true
the result data will be an array of Dirent.namespace readdir
- ): void;
Asynchronously reads the entire contents of a file.
import { readFile } from 'node:fs'; readFile('/etc/passwd', (err, data) => { if (err) throw err; console.log(data); });
The callback is passed two arguments
(err, data)
, wheredata
is the contents of the file.If no encoding is specified, then the raw buffer is returned.
If
options
is a string, then it specifies the encoding:import { readFile } from 'node:fs'; readFile('/etc/passwd', 'utf8', callback);
When the path is a directory, the behavior of
fs.readFile()
and readFileSync is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.import { readFile } from 'node:fs'; // macOS, Linux, and Windows readFile('<directory>', (err, data) => { // => [Error: EISDIR: illegal operation on a directory, read <directory>] }); // FreeBSD readFile('<directory>', (err, data) => { // => null, <data> });
It is possible to abort an ongoing request using an
AbortSignal
. If a request is aborted the callback is called with anAbortError
:import { readFile } from 'node:fs'; const controller = new AbortController(); const signal = controller.signal; readFile(fileInfo[0].name, { signal }, (err, buf) => { // ... }); // When you want to abort the request controller.abort();
The
fs.readFile()
function buffers the entire file. To minimize memory costs, when possible prefer streaming viafs.createReadStream()
.Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering
fs.readFile
performs.@param pathfilename or file descriptor
callback: (err: null | ErrnoException, data: string) => void): void;Asynchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param optionsEither the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to
'r'
.): void;Asynchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param optionsEither the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to
'r'
.): void;Asynchronously reads the entire contents of a file.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.namespace readFile
- callback: (err: null | ErrnoException, linkString: string) => void): void;
Reads the contents of the symbolic link referred to by
path
. The callback gets two arguments(err, linkString)
.See the POSIX
readlink(2)
documentation for more details.The optional
options
argument can be a string specifying an encoding, or an object with anencoding
property specifying the character encoding to use for the link path passed to the callback. If theencoding
is set to'buffer'
, the link path returned will be passed as aBuffer
object.): void;Asynchronous readlink(2) - read value of a symbolic link.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.): void;Asynchronous readlink(2) - read value of a symbolic link.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.@param optionsThe encoding (or an object specifying the encoding), used as the encoding of the result. If not provided,
'utf8'
is used.namespace readlink
- fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],cb: (err: null | ErrnoException, bytesRead: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;
Read from a file specified by
fd
and write to an array ofArrayBufferView
s usingreadv()
.position
is the offset from the beginning of the file from where data should be read. Iftypeof position !== 'number'
, the data will be read from the current position.The callback will be given three arguments:
err
,bytesRead
, andbuffers
.bytesRead
is how many bytes were read from the file.If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffers
properties.fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],position: null | number,cb: (err: null | ErrnoException, bytesRead: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;Read from a file specified by
fd
and write to an array ofArrayBufferView
s usingreadv()
.position
is the offset from the beginning of the file from where data should be read. Iftypeof position !== 'number'
, the data will be read from the current position.The callback will be given three arguments:
err
,bytesRead
, andbuffers
.bytesRead
is how many bytes were read from the file.If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesRead
andbuffers
properties.namespace readv
- ): void;
Asynchronously rename file at
oldPath
to the pathname provided asnewPath
. In the case thatnewPath
already exists, it will be overwritten. If there is a directory atnewPath
, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.See also:
rename(2)
.import { rename } from 'node:fs'; rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; console.log('Rename complete!'); });
namespace rename
- ): void;
Asynchronously removes files and directories (modeled on the standard POSIX
rm
utility). No arguments other than a possible exception are given to the completion callback.): void;Asynchronously removes files and directories (modeled on the standard POSIX
rm
utility). No arguments other than a possible exception are given to the completion callback.namespace rm
- ): void;
Asynchronous
rmdir(2)
. No arguments other than a possible exception are given to the completion callback.Using
fs.rmdir()
on a file (not a directory) results in anENOENT
error on Windows and anENOTDIR
error on POSIX.To get a behavior similar to the
rm -rf
Unix command, use rm with options{ recursive: true, force: true }
.): void;Asynchronous
rmdir(2)
. No arguments other than a possible exception are given to the completion callback.Using
fs.rmdir()
on a file (not a directory) results in anENOENT
error on Windows and anENOTDIR
error on POSIX.To get a behavior similar to the
rm -rf
Unix command, use rm with options{ recursive: true, force: true }
.namespace rmdir
- ): void;
Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
): void;Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
): void;Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
): void;Asynchronous
stat(2)
. The callback gets two arguments(err, stats)
wherestats
is anfs.Stats
object.In case of an error, the
err.code
will be one ofCommon System Errors
.stat follows symbolic links. Use lstat to look at the links themselves.
Using
fs.stat()
to check for the existence of a file before callingfs.open()
,fs.readFile()
, orfs.writeFile()
is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; for (let i = 0; i < pathsToCheck.length; i++) { stat(pathsToCheck[i], (err, stats) => { console.log(stats.isDirectory()); console.log(stats); }); }
The resulting output will resemble:
true Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z } false Stats { dev: 16777220, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214074, size: 8, blocks: 8, atimeMs: 1561174616618.8555, mtimeMs: 1561174614584, ctimeMs: 1561174614583.8145, birthtimeMs: 1561174007710.7478, atime: 2019-06-22T03:36:56.619Z, mtime: 2019-06-22T03:36:54.584Z, ctime: 2019-06-22T03:36:54.584Z, birthtime: 2019-06-22T03:26:47.711Z }
namespace stat
- ): void;
Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
): void;Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
): void;Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
): void;Asynchronous
statfs(2)
. Returns information about the mounted file system which containspath
. The callback gets two arguments(err, stats)
wherestats
is anfs.StatFs
object.In case of an error, the
err.code
will be one ofCommon System Errors
.@param pathA path to an existing file or directory on the file system to be queried.
namespace statfs
- ): void;
Creates the link called
path
pointing totarget
. No arguments other than a possible exception are given to the completion callback.See the POSIX
symlink(2)
documentation for more details.The
type
argument is only available on Windows and ignored on other platforms. It can be set to'dir'
,'file'
, or'junction'
. If thetype
argument is not a string, Node.js will autodetecttarget
type and use'file'
or'dir'
. If thetarget
does not exist,'file'
will be used. Windows junction points require the destination path to be absolute. When using'junction'
, thetarget
argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs'; symlink('./mew', './mewtwo', callback);
The above example creates a symbolic link
mewtwo
which points tomew
in the same directory:tree .
. ├── mew └── mewtwo -> ./mew
): void;Asynchronous symlink(2) - Create a new symbolic link to an existing file.
@param targetA path to an existing file. If a URL is provided, it must use the
file:
protocol.@param pathA path to the new symlink. If a URL is provided, it must use the
file:
protocol. - ): void;
Asynchronous truncate(2) - Truncate a file to a specified length.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol.namespace truncate
- ): void;
Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
import { unlink } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. unlink('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was deleted'); });
fs.unlink()
will not work on a directory, empty or otherwise. To remove a directory, use rmdir.See the POSIX
unlink(2)
documentation for more details.namespace unlink
- ): void;
Change the file system timestamps of the object referenced by
path
.The
atime
andmtime
arguments follow these rules:- Values can be either numbers representing Unix epoch time in seconds,
Date
s, or a numeric string like'123456789.0'
. - If the value can not be converted to a number, or is
NaN
,Infinity
, or-Infinity
, anError
will be thrown.
namespace utimes
- Values can be either numbers representing Unix epoch time in seconds,
- fd: number,buffer: TBuffer,offset?: null | number,length?: null | number,position?: null | number,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;
Write
buffer
to the file specified byfd
.offset
determines the part of the buffer to be written, andlength
is an integer specifying the number of bytes to write.position
refers to the offset from the beginning of the file where this data should be written. Iftypeof position !== 'number'
, the data will be written at the current position. Seepwrite(2)
.The callback will be given three arguments
(err, bytesWritten, buffer)
wherebytesWritten
specifies how many bytes were written frombuffer
.If this method is invoked as its
util.promisify()
ed version, it returns a promise for anObject
withbytesWritten
andbuffer
properties.It is unsafe to use
fs.write()
multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
fd: number,buffer: TBuffer,offset: undefined | null | number,length: undefined | null | number,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
buffer
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param offsetThe part of the buffer to be written. If not supplied, defaults to
0
.@param lengthThe number of bytes to write. If not supplied, defaults to
buffer.length - offset
.fd: number,buffer: TBuffer,offset: undefined | null | number,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
buffer
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param offsetThe part of the buffer to be written. If not supplied, defaults to
0
.fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
buffer
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
fd: number,string: string,position: undefined | null | number,encoding: undefined | null | BufferEncoding,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
string
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
@param positionThe offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
@param encodingThe expected string encoding.
fd: number,string: string,position: undefined | null | number,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
string
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
@param positionThe offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
fd: number,string: string,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
string
to the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
namespace write
- data: string | ArrayBufferView<ArrayBufferLike>,): void;
When
file
is a filename, asynchronously writes data to the file, replacing the file if it already exists.data
can be a string or a buffer.When
file
is a file descriptor, the behavior is similar to callingfs.write()
directly (which is recommended). See the notes below on using a file descriptor.The
encoding
option is ignored ifdata
is a buffer.The
mode
option only affects the newly created file. See open for more details.import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, (err) => { if (err) throw err; console.log('The file has been saved!'); });
If
options
is a string, then it specifies the encoding:import { writeFile } from 'node:fs'; writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
It is unsafe to use
fs.writeFile()
multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.Similarly to
fs.readFile
-fs.writeFile
is a convenience method that performs multiplewrite
calls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.It is possible to use an
AbortSignal
to cancel anfs.writeFile()
. Cancelation is "best effort", and some amount of data is likely still to be written.import { writeFile } from 'node:fs'; import { Buffer } from 'node:buffer'; const controller = new AbortController(); const { signal } = controller; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, { signal }, (err) => { // When a request is aborted - the callback is called with an AbortError }); // When the request should be aborted controller.abort();
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering
fs.writeFile
performs.@param filefilename or file descriptor
data: string | ArrayBufferView<ArrayBufferLike>,): void;Asynchronously writes data to a file, replacing the file if it already exists.
@param pathA path to a file. If a URL is provided, it must use the
file:
protocol. If a file descriptor is provided, the underlying file will not be closed automatically.@param dataThe data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
namespace writeFile
- fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],cb: (err: null | ErrnoException, bytesWritten: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;
Write an array of
ArrayBufferView
s to the file specified byfd
usingwritev()
.position
is the offset from the beginning of the file where this data should be written. Iftypeof position !== 'number'
, the data will be written at the current position.The callback will be given three arguments:
err
,bytesWritten
, andbuffers
.bytesWritten
is how many bytes were written frombuffers
.If this method is
util.promisify()
ed, it returns a promise for anObject
withbytesWritten
andbuffers
properties.It is unsafe to use
fs.writev()
multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
fd: number,buffers: readonly ArrayBufferView<ArrayBufferLike>[],position: null | number,cb: (err: null | ErrnoException, bytesWritten: number, buffers: ArrayBufferView<ArrayBufferLike>[]) => void): void;Write an array of
ArrayBufferView
s to the file specified byfd
usingwritev()
.position
is the offset from the beginning of the file where this data should be written. Iftypeof position !== 'number'
, the data will be written at the current position.The callback will be given three arguments:
err
,bytesWritten
, andbuffers
.bytesWritten
is how many bytes were written frombuffers
.If this method is
util.promisify()
ed, it returns a promise for anObject
withbytesWritten
andbuffers
properties.It is unsafe to use
fs.writev()
multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
namespace writev
interface BigIntOptions
interface BigIntStats
interface BigIntStatsFs
interface CopyOptions
- force?: boolean
Overwrite existing file or directory. _The copy operation will ignore errors if you set this to false and the destination exists. Use the
errorOnExist
option to change this behavior. - source: string,destination: string): boolean | Promise<boolean>;
Function to filter copied files/directories. Return
true
to copy the item,false
to ignore it.
interface CopySyncOptions
- force?: boolean
Overwrite existing file or directory. _The copy operation will ignore errors if you set this to false and the destination exists. Use the
errorOnExist
option to change this behavior. - source: string,destination: string): boolean;
Function to filter copied files/directories. Return
true
to copy the item,false
to ignore it.
interface FSWatcher
The
EventEmitter
class is defined and exposed by thenode:events
module:import { EventEmitter } from 'node:events';
All
EventEmitter
s emit the event'newListener'
when new listeners are added and'removeListener'
when existing listeners are removed.It supports the following option:
- event: string,listener: (...args: any[]) => void): this;
events.EventEmitter
- change
- close
- error
event: 'change',): this;Alias for
emitter.on(eventName, listener)
.event: 'error',): this;Alias for
emitter.on(eventName, listener)
. Stop watching for changes on the given
fs.FSWatcher
. Once stopped, thefs.FSWatcher
object is no longer usable.- eventName: string | symbol,...args: AnyRest): boolean;
Synchronously calls each of the listeners registered for the event named
eventName
, in the order they were registered, passing the supplied arguments to each.Returns
true
if the event had listeners,false
otherwise.import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener
Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbol
s.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the
EventEmitter
which is either set byemitter.setMaxListeners(n)
or defaults to EventEmitter.defaultMaxListeners.- eventName: string | symbol,listener?: Function): number;
Returns the number of listeners listening for the event named
eventName
. Iflistener
is provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
.server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ]
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.removeListener()
. - on(event: string,listener: (...args: any[]) => void): this;
Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
on(event: 'change',): this;Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
on(event: 'close',listener: () => void): this;Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
on(event: 'error',): this;Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
- once(event: string,listener: (...args: any[]) => void): this;
Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
once(event: 'change',): this;Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
once(event: 'close',listener: () => void): this;Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
once(event: 'error',): this;Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param listenerThe callback function
- event: string,listener: (...args: any[]) => void): this;
Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
event: 'change',): this;Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
event: 'close',listener: () => void): this;Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
event: 'error',): this;Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
- event: string,listener: (...args: any[]) => void): this;
Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
event: 'change',): this;Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
event: 'close',listener: () => void): this;Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
event: 'error',): this;Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param listenerThe callback function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
, including any wrappers (such as those created by.once()
).import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log');
When called, requests that the Node.js event loop not exit so long as the
fs.FSWatcher
is active. Callingwatcher.ref()
multiple times will have no effect.By default, all
fs.FSWatcher
objects are "ref'ed", making it normally unnecessary to callwatcher.ref()
unlesswatcher.unref()
had been called previously.- eventName?: string | symbol): this;
Removes all listeners, or those of the specified
eventName
.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter
instance was created by some other component or module (e.g. sockets or file streams).Returns a reference to the
EventEmitter
, so that calls can be chained. - eventName: string | symbol,listener: (...args: any[]) => void): this;
Removes the specified
listener
from the listener array for the event namedeventName
.const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
removeListener()
will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specifiedeventName
, thenremoveListener()
must be called multiple times to remove each instance.Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any
removeListener()
orremoveAllListeners()
calls after emitting and before the last listener finishes execution will not remove them fromemit()
in progress. Subsequent events behave as expected.import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the
emitter.listeners()
method will need to be recreated.When a single function has been added as a handler multiple times for a single event (as in the example below),
removeListener()
will remove the most recently added instance. In the example theonce('ping')
listener is removed:import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');
Returns a reference to the
EventEmitter
, so that calls can be chained. - n: number): this;
By default
EventEmitter
s will print a warning if more than10
listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()
method allows the limit to be modified for this specificEventEmitter
instance. The value can be set toInfinity
(or0
) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter
, so that calls can be chained. When called, the active
fs.FSWatcher
object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before thefs.FSWatcher
object's callback is invoked. Callingwatcher.unref()
multiple times will have no effect.
interface GlobOptions
interface GlobOptionsWithFileTypes
interface GlobOptionsWithoutFileTypes
- exclude?: readonly string[] | (fileName: string) => boolean
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return
true
to exclude the item,false
to include it.
interface MakeDirectoryOptions
- recursive?: boolean
Indicates whether parent folders should be created. If a folder was created, the path to the first created folder will be returned.
interface ObjectEncodingOptions
interface OpenAsBlobOptions
interface OpenDirOptions
- bufferSize?: number
Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage.
interface ReadAsyncOptions<TBuffer extends NodeJS.ArrayBufferView>
interface ReadSyncOptions
interface ReadVResult
interface RmDirOptions
- maxRetries?: number
If an
EBUSY
,EMFILE
,ENFILE
,ENOTEMPTY
, orEPERM
error is encountered, Node.js will retry the operation with a linear backoff wait ofretryDelay
ms longer on each try. This option represents the number of retries. This option is ignored if therecursive
option is nottrue
. - retryDelay?: number
The amount of time in milliseconds to wait between retries. This option is ignored if the
recursive
option is nottrue
.
interface RmOptions
- maxRetries?: number
If an
EBUSY
,EMFILE
,ENFILE
,ENOTEMPTY
, orEPERM
error is encountered, Node.js will retry the operation with a linear backoff wait ofretryDelay
ms longer on each try. This option represents the number of retries. This option is ignored if therecursive
option is nottrue
. - recursive?: boolean
If
true
, perform a recursive directory removal. In recursive mode, operations are retried on failure. - retryDelay?: number
The amount of time in milliseconds to wait between retries. This option is ignored if the
recursive
option is nottrue
.
interface StatFsOptions
interface StatOptions
interface StatsBase<T>
interface StatSyncFn
- readonly name: string
Returns the name of the function. Function names are read-only and can not be changed.
- value: any): boolean;
Determines whether the given value inherits from this function if this function was used as a constructor function.
A constructor function can control which objects are recognized as its instances by 'instanceof' by overriding this method.
- this: Function,thisArg: any,argArray?: any): any;
Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.
@param thisArgThe object to be used as the this object.
@param argArrayA set of arguments to be passed to the function.
- bind(this: Function,thisArg: any,...argArray: any[]): any;
For a given function, creates a bound function that has the same body as the original function. The this object of the bound function is associated with the specified object, and has the specified initial parameters.
@param thisArgAn object to which the this keyword can refer inside the new function.
@param argArrayA list of arguments to be passed to the new function.
- call(this: Function,thisArg: any,...argArray: any[]): any;
Calls a method of an object, substituting another object for the current object.
@param thisArgThe object to be used as the current object.
@param argArrayA list of arguments to be passed to the method.
Returns a string representation of a function.
interface StatSyncOptions
interface StatWatcher
Class: fs.StatWatcher
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.on(eventName, listener)
. - eventName: string | symbol,...args: AnyRest): boolean;
Synchronously calls each of the listeners registered for the event named
eventName
, in the order they were registered, passing the supplied arguments to each.Returns
true
if the event had listeners,false
otherwise.import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener
Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbol
s.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the
EventEmitter
which is either set byemitter.setMaxListeners(n)
or defaults to EventEmitter.defaultMaxListeners.- eventName: string | symbol,listener?: Function): number;
Returns the number of listeners listening for the event named
eventName
. Iflistener
is provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
.server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ]
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.removeListener()
. - eventName: string | symbol,listener: (...args: any[]) => void): this;
Adds the
listener
function to the end of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Adds a one-time
listener
function for the event namedeventName
. The next timeeventName
is triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()
method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a
@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Adds the
listener
function to the beginning of the listeners array for the event namedeventName
. No checks are made to see if thelistener
has already been added. Multiple calls passing the same combination ofeventName
andlistener
will result in thelistener
being added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: string | symbol,listener: (...args: any[]) => void): this;
Adds a one-time
listener
function for the event namedeventName
to the beginning of the listeners array. The next timeeventName
is triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });
Returns a reference to the
EventEmitter
, so that calls can be chained.@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName
, including any wrappers (such as those created by.once()
).import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log');
When called, requests that the Node.js event loop not exit so long as the
fs.StatWatcher
is active. Callingwatcher.ref()
multiple times will have no effect.By default, all
fs.StatWatcher
objects are "ref'ed", making it normally unnecessary to callwatcher.ref()
unlesswatcher.unref()
had been called previously.- eventName?: string | symbol): this;
Removes all listeners, or those of the specified
eventName
.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter
instance was created by some other component or module (e.g. sockets or file streams).Returns a reference to the
EventEmitter
, so that calls can be chained. - eventName: string | symbol,listener: (...args: any[]) => void): this;
Removes the specified
listener
from the listener array for the event namedeventName
.const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
removeListener()
will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specifiedeventName
, thenremoveListener()
must be called multiple times to remove each instance.Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any
removeListener()
orremoveAllListeners()
calls after emitting and before the last listener finishes execution will not remove them fromemit()
in progress. Subsequent events behave as expected.import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the
emitter.listeners()
method will need to be recreated.When a single function has been added as a handler multiple times for a single event (as in the example below),
removeListener()
will remove the most recently added instance. In the example theonce('ping')
listener is removed:import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');
Returns a reference to the
EventEmitter
, so that calls can be chained. - n: number): this;
By default
EventEmitter
s will print a warning if more than10
listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()
method allows the limit to be modified for this specificEventEmitter
instance. The value can be set toInfinity
(or0
) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter
, so that calls can be chained. When called, the active
fs.StatWatcher
object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before thefs.StatWatcher
object's callback is invoked. Callingwatcher.unref()
multiple times will have no effect.
interface WatchFileOptions
Watch for changes on
filename
. The callbacklistener
will be called each time the file is accessed.The
options
argument may be omitted. If provided, it should be an object. Theoptions
object may contain a boolean namedpersistent
that indicates whether the process should continue to run as long as files are being watched. Theoptions
object may specify aninterval
property indicating how often the target should be polled in milliseconds.The
listener
gets two arguments the current stat object and the previous stat object:import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); });
These stat objects are instances of
fs.Stat
. If thebigint
option istrue
, the numeric values in these objects are specified asBigInt
s.To be notified when the file was modified, not just accessed, it is necessary to compare
curr.mtimeMs
andprev.mtimeMs
.When an
fs.watchFile
operation results in anENOENT
error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.Using watch is more efficient than
fs.watchFile
andfs.unwatchFile
.fs.watch
should be used instead offs.watchFile
andfs.unwatchFile
when possible.When a file being watched by
fs.watchFile()
disappears and reappears, then the contents ofprevious
in the second callback event (the file's reappearance) will be the same as the contents ofprevious
in the first callback event (its disappearance).This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name
interface WatchOptions
- signal?: AbortSignal
When provided the corresponding
AbortController
can be used to cancel an asynchronous action.
interface WriteVResult
- type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void
- type BufferEncodingOption = 'buffer' | { encoding: 'buffer' }
- type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null
- type Mode = number | string
- type NoParamCallback = (err: NodeJS.ErrnoException | null) => void
- type OpenMode = number | string
- type PathOrFileDescriptor = PathLike | number
- type ReadPosition = number | bigint
- type StatsListener = (curr: Stats, prev: Stats) => void
- type TimeLike = string | number | Date
- type WatchEventType = 'rename' | 'change'
- type WatchListener<T> = (event: WatchEventType, filename: T | null) => void
- type WriteFileOptions = ObjectEncodingOptions & Abortable & { flag: string; flush: boolean; mode: Mode } | BufferEncoding | null