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
callbackgets two arguments(err, resolvedPath). May useprocess.cwdto resolve relative paths.Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.If
pathresolves to a socket or a pipe, the function will return a system dependent name for that object.callback: (err: null | ErrnoException, resolvedPath: NonSharedBuffer) => 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.@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 | NonSharedBuffer) => 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.@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
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: NonSharedBuffer) => void): void;Asynchronous
realpath(3).The
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: string | NonSharedBuffer) => void): void;Asynchronous
realpath(3).The
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: string) => void): void;Asynchronous
realpath(3).The
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin 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.
): NonSharedBuffer;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.): string | NonSharedBuffer;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.Dirobject 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(). Calls
dir.close()if the directory handle is open, and returns a promise that fulfills when disposal is complete.Asynchronously iterates over the directory via
readdir(3)until all entries have been read.Calls
dir.closeSync()if the directory handle is open, and returnsundefined.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, ornullif 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, ornullif 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,
nullwill 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<Name extends string | Buffer = string>
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
withFileTypesoption set totrue, the resulting array is filled withfs.Direntobjects, rather than strings orBuffers.- name: Name
The file name that this
fs.Direntobject refers to. The type of this value is determined by theoptions.encodingpassed to readdir or readdirSync. Returns
trueif thefs.Direntobject describes a block device.Returns
trueif thefs.Direntobject describes a character device.Returns
trueif thefs.Direntobject describes a file system directory.Returns
trueif thefs.Direntobject describes a first-in-first-out (FIFO) pipe.Returns
trueif thefs.Direntobject describes a regular file.Returns
trueif thefs.Direntobject describes a socket.Returns
trueif thefs.Direntobject describes a symbolic link.
class ReadStream
Instances of
fs.ReadStreamare 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(). Ifpathis passed as a string, thenreadStream.pathwill be a string. Ifpathis passed as aBuffer, thenreadStream.pathwill be aBuffer. Iffdis specified, thenreadStream.pathwill beundefined. - pending: boolean
This property is
trueif the underlying file has not been opened yet, i.e. before the'ready'event is emitted. - readable: boolean
Is
trueif 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
encodingof a givenReadablestream. Theencodingproperty can be set using the setEncoding method. - readonly readableFlowing: null | boolean
This property reflects the current state of a
Readablestream as described in the Three states section. - readonly readableHighWaterMark: number
Returns the value of
highWaterMarkpassed 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
captureRejectionsoption on all newEventEmitterobjects. - 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
10listeners can be registered for any single event. This limit can be changed for individualEventEmitterinstances using theemitter.setMaxListeners(n)method. To change the default for allEventEmitterinstances, theevents.defaultMaxListenersproperty can be used. If this value is not a positive number, aRangeErroris thrown.Take caution when setting the
events.defaultMaxListenersbecause the change affects allEventEmitterinstances, including those created before the change is made. However, callingemitter.setMaxListeners(n)still has precedence overevents.defaultMaxListeners.This is not a hard limit. The
EventEmitterinstance 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-warningscommand-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, andcountproperties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Itsnameproperty 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 anAbortErrorand returns a promise that fulfills when the stream is finished.- @returns
AsyncIteratorto fully consume the stream. - 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 is0and 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 (unlessemitCloseis 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
trueif the event had listeners,falseotherwise.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
Symbols.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.everyand 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 chunkawaited 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
trueif 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
awaited.@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.findand 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
undefinedif no element was found.find(): Promise<any>;This method is similar to
Array.prototype.findand 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
undefinedif 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
awaited.This method is different from
for await...ofloops in that it can optionally process chunks concurrently. In addition, aforEachiteration can only be stopped by having passed asignaloption and aborting the related AbortController whilefor await...ofcan be stopped withbreakorreturn. In either case the stream will be destroyed.This method is different from listening to the
'data'event in that it uses thereadableevent 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
EventEmitterwhich 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...ofloop 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. Iflisteneris 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
awaited 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
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventName. The next timeeventNameis 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
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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,nullis returned. By default, the data is returned as aBufferobject unless an encoding has been specified using thereadable.setEncoding()method or the stream is operating in object mode.The optional
sizeargument specifies a specific number of bytes to read. Ifsizebytes are not available to be read,nullwill be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.If the
sizeargument is not specified, all of the data contained in the internal buffer will be returned.The
sizeargument must be less than or equal to 1 GiB.The
readable.read()method should only be called onReadablestreams 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. Awhileloop 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
Readablestream in object mode will always return a single item from a call toreadable.read(size), regardless of the value of thesizeargument.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
TypeErrorwith theERR_INVALID_ARGScode 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.mapmethod.@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
TypeErrorwith theERR_INVALID_ARGScode 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.mapmethod.@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
EventEmitterinstance 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
listenerfrom 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: // ABecause 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 pausedReadablestream 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 theReadablestream.By default, no encoding is assigned and stream data will be returned as
Bufferobjects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than asBufferobjects. 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
Readablestream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream asBufferobjects.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
EventEmitters will print a warning if more than10listeners 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 specificEventEmitterinstance. 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.someand calls fn on each chunk in the stream until the awaited return value istrue(or any truthy value). Once an fn call on a chunkawaited 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
trueif 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 aWritablestream previously attached using the pipe method.If the
destinationis not specified, then all pipes are detached.If the
destinationis 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
chunkasnullsignals 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 aTransformstream instead. See theAPI for stream implementerssection 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,
chunkmust be a {string}, {Buffer}, {TypedArray}, {DataView} ornull. For object mode streams,chunkmay be any JavaScript value.@param encodingEncoding of string chunks. Must be a valid
Bufferencoding, such as'utf8'or'ascii'. - wrap(stream: ReadableStream): this;
Prior to Node.js 0.10, streams did not implement the entire
node:streammodule API as it is currently defined. (SeeCompatibilityfor 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 aReadablestream 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
abortevent on the providedsignal.Listening to the
abortevent 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
AbortSignals in Node.js APIs by solving these two issues by listening to the event such thatstopImmediatePropagationdoes 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
abortlistener. - iterable: Iterable<any, any, any> | AsyncIterable<any, any, any>,
A utility method for creating Readable Streams out of iterators.
@param iterableObject implementing the
Symbol.asyncIteratororSymbol.iteratoriterable 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.objectModetotrue, unless this is explicitly opted out by settingoptions.objectModetofalse. A utility method for creating a
Readablefrom a webReadableStream.- name: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName.For
EventEmitters this behaves exactly the same as calling.listenerson the emitter.For
EventTargets 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
EventEmitters this behaves exactly the same as calling.getMaxListenerson the emitter.For
EventTargets 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 hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan 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
closeoption 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
AsyncIteratorthat iterateseventNameevents emitted by theemittereventName: 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 hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan 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
closeoption 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
AsyncIteratorthat iterateseventNameevents emitted by theemitter - emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterOptions): Promise<any[]>;
Creates a
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill 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 boomAn
AbortSignalcan 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
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill 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 boomAn
AbortSignalcan 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
EventTargetevent.@param eventTargetsZero or more {EventTarget} or {EventEmitter} instances. If none are specified,
nis set as the default max for all newly created {EventTarget} and {EventEmitter} objects. A utility method for creating a web
ReadableStreamfrom aReadable.
class Stats
A
fs.Statsobject provides information about a file.Objects returned from stat, lstat, fstat, and their synchronous counterparts are of this type. If
bigintin theoptionspassed to those methods is true, the numeric values will bebigintinstead ofnumber, and the object will contain additional nanosecond-precision properties suffixed withNs.Statobjects are not to be created directly using thenewkeyword.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 }bigintversion: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
bigintin theoptionspassed to those methods istrue, the numeric values will bebigintinstead ofnumber.StatFs { type: 1397114950, bsize: 4096, blocks: 121938943, bfree: 61058895, bavail: 61058895, files: 999, ffree: 1000000 }bigintversion:StatFs { type: 1397114950n, bsize: 4096n, blocks: 121938943n, bfree: 61058895n, bavail: 61058895n, files: 999n, ffree: 1000000n }class Utf8Stream
An optimized UTF-8 stream writer that allows for flushing all the internal buffering on demand. It handles
EAGAINerrors correctly, allowing for customization, for example, by dropping content if the disk is busy.- readonly contentMode: 'utf8' | 'buffer'
The type of data that can be written to the stream. Supported values are
'utf8'or'buffer'. - readonly fsync: boolean
Whether the stream is performing a
fs.fsyncSync()after every write operation. - readonly maxLength: number
The maximum length of the internal buffer. If a write operation would cause the buffer to exceed
maxLength, the data written is dropped and a drop event is emitted with the dropped data. - readonly minLength: number
The minimum length of the internal buffer that is required to be full before flushing.
- readonly mkdir: boolean
Whether the stream should ensure that the directory for the
destfile exists. Iftrue, it will create the directory if it does not exist. - readonly periodicFlush: number
The number of milliseconds between flushes. If set to
0, no periodic flushes will be performed. - static captureRejections: boolean
Value: boolean
Change the default
captureRejectionsoption on all newEventEmitterobjects. - 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
10listeners can be registered for any single event. This limit can be changed for individualEventEmitterinstances using theemitter.setMaxListeners(n)method. To change the default for allEventEmitterinstances, theevents.defaultMaxListenersproperty can be used. If this value is not a positive number, aRangeErroris thrown.Take caution when setting the
events.defaultMaxListenersbecause the change affects allEventEmitterinstances, including those created before the change is made. However, callingemitter.setMaxListeners(n)still has precedence overevents.defaultMaxListeners.This is not a hard limit. The
EventEmitterinstance 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-warningscommand-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, andcountproperties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Itsnameproperty 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
utf8Stream.destroy().- event: 'drop',): this;
events.EventEmitter
- change
- close
- error
event: 'error',): this;events.EventEmitter
- change
- close
- error
event: string,listener: (...args: any[]) => void): this;events.EventEmitter
- change
- close
- error
Close the stream immediately, without flushing the internal buffer.
- 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
trueif the event had listeners,falseotherwise.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 Close the stream gracefully, flushing the internal buffer before closing.
Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbols.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) ]Flushes the buffered data synchronously. This is a costly operation.
Returns the current max listener value for the
EventEmitterwhich 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. Iflisteneris 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: 'close',listener: () => void): this;
Adds the
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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: 'close',listener: () => void): this;
Adds a one-time
listenerfunction for the event namedeventName. The next timeeventNameis 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: 'close',listener: () => void): this;
Adds the
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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 a one-time
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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: 'drop',): this; - 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
EventEmitterinstance 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
listenerfrom 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: // ABecause 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
EventEmitters will print a warning if more than10listeners 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 specificEventEmitterinstance. 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. - ): Disposable;
Listens once to the
abortevent on the providedsignal.Listening to the
abortevent 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
AbortSignals in Node.js APIs by solving these two issues by listening to the event such thatstopImmediatePropagationdoes 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
abortlistener. - name: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName.For
EventEmitters this behaves exactly the same as calling.listenerson the emitter.For
EventTargets 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
EventEmitters this behaves exactly the same as calling.getMaxListenerson the emitter.For
EventTargets 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 hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan 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
closeoption 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
AsyncIteratorthat iterateseventNameevents emitted by theemittereventName: 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 hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan 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
closeoption 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
AsyncIteratorthat iterateseventNameevents emitted by theemitter - emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterOptions): Promise<any[]>;
Creates a
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill 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 boomAn
AbortSignalcan 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
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill 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 boomAn
AbortSignalcan 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
EventTargetevent.@param eventTargetsZero or more {EventTarget} or {EventEmitter} instances. If none are specified,
nis set as the default max for all newly created {EventTarget} and {EventEmitter} objects.
class WriteStream
- Extends
stream.Writable
Instances of
fs.WriteStreamare 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
trueif the underlying file has not been opened yet, i.e. before the'ready'event is emitted. - readonly writable: boolean
Is
trueif it is safe to callwritable.write(), which means the stream has not been destroyed, errored, or ended. - readonly writableAborted: boolean
Returns whether the stream was destroyed or errored before emitting
'finish'. - readonly writableCorked: number
Number of times
writable.uncork()needs to be called in order to fully uncork the stream. - readonly writableEnded: boolean
Is
trueafterwritable.end()has been called. This property does not indicate whether the data has been flushed, for this usewritable.writableFinishedinstead. - readonly writableHighWaterMark: number
Return the value of
highWaterMarkpassed 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
trueif the stream's buffer has been full and stream will emit'drain'. - static captureRejections: boolean
Value: boolean
Change the default
captureRejectionsoption on all newEventEmitterobjects. - 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
10listeners can be registered for any single event. This limit can be changed for individualEventEmitterinstances using theemitter.setMaxListeners(n)method. To change the default for allEventEmitterinstances, theevents.defaultMaxListenersproperty can be used. If this value is not a positive number, aRangeErroris thrown.Take caution when setting the
events.defaultMaxListenersbecause the change affects allEventEmitterinstances, including those created before the change is made. However, callingemitter.setMaxListeners(n)still has precedence overevents.defaultMaxListeners.This is not a hard limit. The
EventEmitterinstance 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-warningscommand-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, andcountproperties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Itsnameproperty 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
writable.destroy()with anAbortErrorand returns a promise that fulfills when the stream is finished.- 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 thewriteStreamis 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 (unlessemitCloseis set tofalse). After this call, the writable stream has ended and subsequent calls towrite()orend()will result in anERR_STREAM_DESTROYEDerror. This is a destructive and immediate way to destroy a stream. Previous calls towrite()may not have drained, and may trigger anERR_STREAM_DESTROYEDerror. 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
trueif the event had listeners,falseotherwise.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 optionalchunkandencodingarguments 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 optionalchunkandencodingarguments 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,
chunkmust be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunkmay 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 optionalchunkandencodingarguments 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,
chunkmust be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunkmay be any JavaScript value other thannull.@param encodingThe encoding if
chunkis a string Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbols.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
EventEmitterwhich 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. Iflisteneris 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
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventName. The next timeeventNameis 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
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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
EventEmitterinstance 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
listenerfrom 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: // ABecause 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 defaultencodingfor aWritablestream.@param encodingThe new default encoding
- n: number): this;
By default
EventEmitters will print a warning if more than10listeners 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 specificEventEmitterinstance. 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 suppliedcallbackonce the data has been fully handled. If an error occurs, thecallbackwill be called with the error as its first argument. Thecallbackis called asynchronously and before'error'is emitted.The return value is
trueif the internal buffer is less than thehighWaterMarkconfigured when the stream was created after admittingchunk. Iffalseis 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 theTransformstreams 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
Readableand 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
Writablestream in object mode will always ignore theencodingargument.@param chunkOptional data to write. For streams not operating in object mode,
chunkmust be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunkmay be any JavaScript value other thannull.@param callbackCallback for when this chunk of data is flushed.
@returnsfalseif 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 suppliedcallbackonce the data has been fully handled. If an error occurs, thecallbackwill be called with the error as its first argument. Thecallbackis called asynchronously and before'error'is emitted.The return value is
trueif the internal buffer is less than thehighWaterMarkconfigured when the stream was created after admittingchunk. Iffalseis 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 theTransformstreams 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
Readableand 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
Writablestream in object mode will always ignore theencodingargument.@param chunkOptional data to write. For streams not operating in object mode,
chunkmust be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,chunkmay be any JavaScript value other thannull.@param encodingThe encoding, if
chunkis a string.@param callbackCallback for when this chunk of data is flushed.
@returnsfalseif 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
abortevent on the providedsignal.Listening to the
abortevent 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
AbortSignals in Node.js APIs by solving these two issues by listening to the event such thatstopImmediatePropagationdoes 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
abortlistener. - options?: Pick<WritableOptions<Writable>, 'signal' | 'decodeStrings' | 'highWaterMark' | 'objectMode'>
A utility method for creating a
Writablefrom a webWritableStream. - name: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName.For
EventEmitters this behaves exactly the same as calling.listenerson the emitter.For
EventTargets 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
EventEmitters this behaves exactly the same as calling.getMaxListenerson the emitter.For
EventTargets 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 hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan 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
closeoption 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
AsyncIteratorthat iterateseventNameevents emitted by theemittereventName: 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 hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan 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
closeoption 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
AsyncIteratorthat iterateseventNameevents emitted by theemitter - emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterOptions): Promise<any[]>;
Creates a
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill 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 boomAn
AbortSignalcan 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
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill 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 boomAn
AbortSignalcan 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
EventTargetevent.@param eventTargetsZero or more {EventTarget} or {EventEmitter} instances. If none are specified,
nis set as the default max for all newly created {EventTarget} and {EventEmitter} objects. A utility method for creating a web
WritableStreamfrom 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. Themodeargument is an optional integer that specifies the accessibility checks to be performed.modeshould be either the valuefs.constants.F_OKor 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 constantsfor 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 anErrorobject. The following examples check ifpackage.jsonexists, 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. Themodeargument is an optional integer that specifies the accessibility checks to be performed.modeshould be either the valuefs.constants.F_OKor 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 constantsfor possible values ofmode.If any of the accessibility checks fail, an
Errorwill 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.
datacan be a string or aBuffer.The
modeoption 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
optionsis a string, then it specifies the encoding:import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback);The
pathmay 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.
datacan be a string or aBuffer.The
modeoption 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
optionsis a string, then it specifies the encoding:import { appendFileSync } from 'node:fs'; appendFileSync('message.txt', 'data to append', 'utf8');The
pathmay 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 otherfsoperation may lead to undefined behavior.See the POSIX
close(2)documentation for more detail. - ): void;
Asynchronously copies
srctodest. By default,destis 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.modeis an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);@param srcsource filename to copy
@param destdestination filename of the copy operation
mode: number,): void;Asynchronously copies
srctodest. By default,destis 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.modeis an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);@param srcsource filename to copy
@param destdestination filename of the copy operation
@param modemodifiers for copy operation.
- mode?: number): void;
Synchronously copies
srctodest. By default,destis 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.modeis an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFileSync, constants } from 'node:fs'; // destination.txt will be created or overwritten by default. copyFileSync('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);@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
srctodest, 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
srctodest, 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
srctodest, 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
optionscan includestartandendvalues to read a range of bytes from the file instead of the entire file. Bothstartandendare inclusive and start counting at 0, allowed values are in the [0,Number.MAX_SAFE_INTEGER] range. Iffdis specified andstartis omitted orundefined,fs.createReadStream()reads sequentially from the current file position. Theencodingcan be any one of those accepted byBuffer.If
fdis specified,ReadStreamwill ignore thepathargument and will use the specified file descriptor. This means that no'open'event will be emitted.fdshould be blocking; non-blockingfds should be passed tonet.Socket.If
fdpoints 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 theemitCloseoption tofalseto change this behavior.By providing the
fsoption, it is possible to override the correspondingfsimplementations foropen,read, andclose. When providing thefsoption, an override forreadis required. If nofdis provided, an override foropenis also required. IfautoCloseistrue, an override forcloseis 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
autoCloseis 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. IfautoCloseis set to true (default behavior), on'error'or'end'the file descriptor will be closed automatically.modesets 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
optionsis a string, then it specifies the encoding. - options?: BufferEncoding | WriteStreamOptions
optionsmay also include astartoption 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 theflagsoption to be set tor+rather than the defaultw. Theencodingcan be any one of those accepted byBuffer.If
autoCloseis set to true (default behavior) on'error'or'finish'the file descriptor will be closed automatically. IfautoCloseis 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 theemitCloseoption tofalseto change this behavior.By providing the
fsoption it is possible to override the correspondingfsimplementations foropen,write,writev, andclose. Overridingwrite()withoutwritev()can reduce performance as some optimizations (_writev()) will be disabled. When providing thefsoption, overrides for at least one ofwriteandwritevare required. If nofdoption is supplied, an override foropenis also required. IfautoCloseistrue, an override forcloseis also required.Like
fs.ReadStream, iffdis specified,fs.WriteStreamwill ignore thepathargument and will use the specified file descriptor. This means that no'open'event will be emitted.fdshould be blocking; non-blockingfds should be passed tonet.Socket.If
optionsis 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.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail. - fd: number,
Retrieves the
fs.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail.fd: number,Retrieves the
fs.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail.fd: number,Retrieves the
fs.Statsfor 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
lenbytes, only the firstlenbytes 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
lenbytes, it is extended, and the extended part is filled with null bytes ('\0'):If
lenis negative then0will 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 | readonly string[],callback: (err: null | ErrnoException, matches: string[]) => void): void;
Retrieves the files matching the specified pattern.
import { glob } from 'node:fs'; glob('*.js', (err, matches) => { if (err) throw err; console.log(matches); });pattern: string | readonly string[],): void;Retrieves the files matching the specified pattern.
import { glob } from 'node:fs'; glob('*.js', (err, matches) => { if (err) throw err; console.log(matches); });pattern: string | readonly string[],callback: (err: null | ErrnoException, matches: string[]) => void): void;Retrieves the files matching the specified pattern.
import { glob } from 'node:fs'; glob('*.js', (err, matches) => { if (err) throw err; console.log(matches); });pattern: string | readonly string[],): void;Retrieves the files matching the specified pattern.
import { glob } from 'node:fs'; glob('*.js', (err, matches) => { if (err) throw err; console.log(matches); }); - pattern: string | readonly string[]): string[];
import { globSync } from 'node:fs'; console.log(globSync('*.js'));@returnspaths of files that match the pattern.
pattern: string | readonly string[],import { globSync } from 'node:fs'; console.log(globSync('*.js'));@returnspaths of files that match the pattern.
pattern: string | readonly string[],): string[];import { globSync } from 'node:fs'; console.log(globSync('*.js'));@returnspaths of files that match the pattern.
pattern: string | readonly string[],import { globSync } from 'node:fs'; console.log(globSync('*.js'));@returnspaths of files that match the 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
existingPathto 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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
recursiveistrue, the first directory path created,(err[, path]).pathcan still beundefinedwhenrecursiveistrue, if no directory was created (for instance, if it was previously created).The optional
optionsargument can be an integer specifyingmode(permission and sticky bits), or an object with amodeproperty and arecursiveproperty indicating whether parent directories should be created. Callingfs.mkdir()whenpathis a directory that exists results in an error only whenrecursiveis false. Ifrecursiveis false and the directory exists, anEEXISTerror 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 ifrecursiveistrue, 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
prefixto create a unique temporary directory. Due to platform inconsistencies, avoid trailingXcharacters inprefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailingXcharacters inprefixwith random characters.The created directory path is passed as a string to the callback's second parameter.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty 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 theprefixstring. For instance, given a directory/tmp, if the intention is to create a temporary directory within/tmp, theprefixmust 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,callback: (err: null | ErrnoException, folder: NonSharedBuffer) => 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.
@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 | NonSharedBuffer) => 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.
@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,
Returns a disposable object whose
pathproperty holds the created directory path. When the object is disposed, the directory and its contents will be removed if it still exists. If the directory cannot be deleted, disposal will throw an error. The object has aremove()method which will perform the same task.<!-- TODO: link MDN docs for disposables once https://github.com/mdn/content/pull/38027 lands -->
For detailed information, see the documentation of
fs.mkdtemp().There is no callback-based version of this API because it is designed for use with the
usingsyntax.The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use. - prefix: string,): string;
Returns the created directory path.
For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use.prefix: string,): NonSharedBuffer;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,): string | NonSharedBuffer;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.modesets 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 systemflags``.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 systemflags``. Returns a
Blobwhose data is backed by the given file.The file must not be modified after the
Blobis created. Any modifications will cause reading theBlobdata to fail with aDOMExceptionerror. Synchronous stat operations on the file when theBlobis 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
encodingoption sets the encoding for thepathwhile 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
encodingoption sets the encoding for thepathwhile 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
encodingoption sets the encoding for thepathwhile 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 anObjectwithbytesReadandbufferproperties.@param bufferThe buffer that the data will be written to.
@param offsetThe position in
bufferto write the data to.@param lengthThe number of bytes to read.
@param positionSpecifies where to begin reading from in the file. If
positionisnullor-1, data will be read from the current file position, and the file position will be updated. Ifpositionis 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.readfunction, this version takes an optionaloptionsobject. If not otherwise specified in anoptionsobject,bufferdefaults toBuffer.alloc(16384),offsetdefaults to0,lengthdefaults tobuffer.byteLength,- offsetas of Node 17.6.0positiondefaults tonullfd: 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 anObjectwithbytesReadandbufferproperties.@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 anObjectwithbytesReadandbufferproperties.@param bufferThe buffer that the data will be written to.
fd: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: NonSharedBuffer) => 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 anObjectwithbytesReadandbufferproperties. - 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)wherefilesis an array of the names of the files in the directory excluding'.'and'..'.See the POSIX
readdir(3)documentation for more details.The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the filenames passed to the callback. If theencodingis set to'buffer', the filenames returned will be passed asBufferobjects.If
options.withFileTypesis set totrue, thefilesarray will containfs.Direntobjects.options: 'buffer' | { encoding: 'buffer'; recursive: boolean; withFileTypes: false },callback: (err: null | ErrnoException, files: NonSharedBuffer[]) => 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.@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 },callback: (err: null | ErrnoException, files: string[] | NonSharedBuffer[]) => 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.@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: truethe result data will be an array of Dirent.options: { encoding: 'buffer'; recursive: boolean; withFileTypes: true },): 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 optionsMust include
withFileTypes: trueandencoding: 'buffer'. - 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
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the filenames returned. If theencodingis set to'buffer', the filenames returned will be passed asBufferobjects.If
options.withFileTypesis set totrue, the result will containfs.Direntobjects.options: 'buffer' | { encoding: 'buffer'; recursive: boolean; withFileTypes: false }): NonSharedBuffer[];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 }): string[] | NonSharedBuffer[];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: truethe result data will be an array of Dirent.options: { encoding: 'buffer'; recursive: boolean; withFileTypes: true }Synchronous readdir(3) - read a directory.
@param pathA path to a file. If a URL is provided, it must use the
file:protocol.@param optionsMust include
withFileTypes: trueandencoding: 'buffer'. - callback: (err: null | ErrnoException, data: NonSharedBuffer) => void): 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), wheredatais the contents of the file.If no encoding is specified, then the raw buffer is returned.
If
optionsis 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.readFileperforms.@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'.callback: (err: null | ErrnoException, data: string | NonSharedBuffer) => 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'.callback: (err: null | ErrnoException, data: NonSharedBuffer) => 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. - options?: null | { encoding: null; flag: string }): NonSharedBuffer;
Returns the contents of the
path.For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the
encodingoption 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'.): string | NonSharedBuffer;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
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the link path passed to the callback. If theencodingis set to'buffer', the link path returned will be passed as aBufferobject.callback: (err: null | ErrnoException, linkString: NonSharedBuffer) => void): 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.callback: (err: null | ErrnoException, linkString: string | NonSharedBuffer) => void): 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
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the link path returned. If theencodingis set to'buffer', the link path returned will be passed as aBufferobject.): NonSharedBuffer;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.): string | NonSharedBuffer;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.readSyncfunction, this version takes an optionaloptionsobject. If nooptionsobject is specified, it will default with the above values. - fd: number,buffers: TBuffers,cb: (err: null | ErrnoException, bytesRead: number, buffers: TBuffers) => void): void;
Read from a file specified by
fdand write to an array ofArrayBufferViews usingreadv().positionis 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.bytesReadis how many bytes were read from the file.If this method is invoked as its
util.promisify()ed version, it returns a promise for anObjectwithbytesReadandbuffersproperties.fd: number,buffers: TBuffers,position: null | number,cb: (err: null | ErrnoException, bytesRead: number, buffers: TBuffers) => void): void;Read from a file specified by
fdand write to an array ofArrayBufferViews usingreadv().positionis 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.bytesReadis how many bytes were read from the file.If this method is invoked as its
util.promisify()ed version, it returns a promise for anObjectwithbytesReadandbuffersproperties. - 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
callbackgets two arguments(err, resolvedPath). May useprocess.cwdto resolve relative paths.Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.If
pathresolves to a socket or a pipe, the function will return a system dependent name for that object.callback: (err: null | ErrnoException, resolvedPath: NonSharedBuffer) => 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.@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 | NonSharedBuffer) => 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.@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
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: NonSharedBuffer) => void): void;Asynchronous
realpath(3).The
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: string | NonSharedBuffer) => void): void;Asynchronous
realpath(3).The
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin order for this function to work. Glibc does not have this restriction.callback: (err: null | ErrnoException, resolvedPath: string) => void): void;Asynchronous
realpath(3).The
callbackgets two arguments(err, resolvedPath).Only paths that can be converted to UTF8 strings are supported.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the path passed to the callback. If theencodingis set to'buffer', the path returned will be passed as aBufferobject.On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on
/procin 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.
): NonSharedBuffer;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.): string | NonSharedBuffer;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
oldPathto the pathname provided asnewPath. In the case thatnewPathalready 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
oldPathtonewPath. Returnsundefined.See the POSIX
rename(2)documentation for more details. - ): void;
Asynchronously removes files and directories (modeled on the standard POSIX
rmutility). No arguments other than a possible exception are given to the completion callback.): void;Asynchronously removes files and directories (modeled on the standard POSIX
rmutility). 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 anENOENTerror on Windows and anENOTDIRerror on POSIX.To get a behavior similar to the
rm -rfUnix 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 anENOENTerror on Windows and anENOTDIRerror on POSIX.To get a behavior similar to the
rm -rfUnix 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 anENOENTerror on Windows and anENOTDIRerror on POSIX.To get a behavior similar to the
rm -rfUnix command, use rmSync with options{ recursive: true, force: true }. - ): void;
Asynchronous
stat(2). The callback gets two arguments(err, stats)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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.codewill 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.codewill 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.codewill 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
pathpointing totarget. No arguments other than a possible exception are given to the completion callback.See the POSIX
symlink(2)documentation for more details.The
typeargument is only available on Windows and ignored on other platforms. It can be set to'dir','file', or'junction'. If thetypeargument is not a string, Node.js will autodetecttargettype and use'file'or'dir'. If thetargetdoes not exist,'file'will be used. Windows junction points require the destination path to be absolute. When using'junction', thetargetargument 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
mewtwowhich points tomewin 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. Iflisteneris 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. Iflisteneris 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
atimeandmtimearguments follow these rules:- Values can be either numbers representing Unix epoch time in seconds,
Dates, or a numeric string like'123456789.0'. - If the value can not be converted to a number, or is
NaN,Infinity, or-Infinity, anErrorwill be thrown.
- 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, wherefilenameis either a file or a directory.The second argument is optional. If
optionsis provided as a string, it specifies theencoding. Otherwiseoptionsshould be passed as an object.The listener callback gets two arguments
(eventType, filename).eventTypeis either'rename'or'change', andfilenameis 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
signalis passed, aborting the corresponding AbortController will close the returnedfs.FSWatcher.Watch for changes on
filename, wherefilenameis either a file or a directory.The second argument is optional. If
optionsis provided as a string, it specifies theencoding. Otherwiseoptionsshould be passed as an object.The listener callback gets two arguments
(eventType, filename).eventTypeis either'rename'or'change', andfilenameis 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
signalis passed, aborting the corresponding AbortController will close the returnedfs.FSWatcher.Watch for changes on
filename, wherefilenameis either a file or a directory.The second argument is optional. If
optionsis provided as a string, it specifies theencoding. Otherwiseoptionsshould be passed as an object.The listener callback gets two arguments
(eventType, filename).eventTypeis either'rename'or'change', andfilenameis 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
signalis passed, aborting the corresponding AbortController will close the returnedfs.FSWatcher.Watch for changes on
filename, wherefilenameis either a file or a directory.The second argument is optional. If
optionsis provided as a string, it specifies theencoding. Otherwiseoptionsshould be passed as an object.The listener callback gets two arguments
(eventType, filename).eventTypeis either'rename'or'change', andfilenameis 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
signalis passed, aborting the corresponding AbortController will close the returnedfs.FSWatcher.Watch for changes on
filename. The callbacklistenerwill be called each time the file is accessed.The
optionsargument may be omitted. If provided, it should be an object. Theoptionsobject may contain a boolean namedpersistentthat indicates whether the process should continue to run as long as files are being watched. Theoptionsobject may specify anintervalproperty indicating how often the target should be polled in milliseconds.The
listenergets 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 thebigintoption istrue, the numeric values in these objects are specified asBigInts.To be notified when the file was modified, not just accessed, it is necessary to compare
curr.mtimeMsandprev.mtimeMs.When an
fs.watchFileoperation results in anENOENTerror, 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.watchFileandfs.unwatchFile.fs.watchshould be used instead offs.watchFileandfs.unwatchFilewhen possible.When a file being watched by
fs.watchFile()disappears and reappears, then the contents ofpreviousin the second callback event (the file's reappearance) will be the same as the contents ofpreviousin 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 callbacklistenerwill be called each time the file is accessed.The
optionsargument may be omitted. If provided, it should be an object. Theoptionsobject may contain a boolean namedpersistentthat indicates whether the process should continue to run as long as files are being watched. Theoptionsobject may specify anintervalproperty indicating how often the target should be polled in milliseconds.The
listenergets 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 thebigintoption istrue, the numeric values in these objects are specified asBigInts.To be notified when the file was modified, not just accessed, it is necessary to compare
curr.mtimeMsandprev.mtimeMs.When an
fs.watchFileoperation results in anENOENTerror, 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.watchFileandfs.unwatchFile.fs.watchshould be used instead offs.watchFileandfs.unwatchFilewhen possible.When a file being watched by
fs.watchFile()disappears and reappears, then the contents ofpreviousin the second callback event (the file's reappearance) will be the same as the contents ofpreviousin 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 callbacklistenerwill 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
bufferto the file specified byfd.offsetdetermines the part of the buffer to be written, andlengthis an integer specifying the number of bytes to write.positionrefers 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)wherebytesWrittenspecifies how many bytes were written frombuffer.If this method is invoked as its
util.promisify()ed version, it returns a promise for anObjectwithbytesWrittenandbufferproperties.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
bufferto 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
bufferto 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
bufferto the file referenced by the supplied file descriptor.@param fdA file descriptor.
fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
bufferto the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param optionsAn object with the following properties:
offsetThe part of the buffer to be written. If not supplied, defaults to0.lengthThe number of bytes to write. If not supplied, defaults tobuffer.length - offset.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,position: undefined | null | number,encoding: undefined | null | BufferEncoding,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
stringto 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
stringto 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
stringto the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param stringA string to write.
- data: string | ArrayBufferView<ArrayBufferLike>,): void;
When
fileis a filename, asynchronously writes data to the file, replacing the file if it already exists.datacan be a string or a buffer.When
fileis a file descriptor, the behavior is similar to callingfs.write()directly (which is recommended). See the notes below on using a file descriptor.The
encodingoption is ignored ifdatais a buffer.The
modeoption 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
optionsis 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.writeFileis a convenience method that performs multiplewritecalls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.It is possible to use an
AbortSignalto 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.writeFileperforms.@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
modeoption 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
stringto 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: TBuffers,cb: (err: null | ErrnoException, bytesWritten: number, buffers: TBuffers) => void): void;
Write an array of
ArrayBufferViews to the file specified byfdusingwritev().positionis 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.bytesWrittenis how many bytes were written frombuffers.If this method is
util.promisify()ed, it returns a promise for anObjectwithbytesWrittenandbuffersproperties.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: TBuffers,position: null | number,cb: (err: null | ErrnoException, bytesWritten: number, buffers: TBuffers) => void): void;Write an array of
ArrayBufferViews to the file specified byfdusingwritev().positionis 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.bytesWrittenis how many bytes were written frombuffers.If this method is
util.promisify()ed, it returns a promise for anObjectwithbytesWrittenandbuffersproperties.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. Themodeargument is an optional integer that specifies the accessibility checks to be performed.modeshould be either the valuefs.constants.F_OKor 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 constantsfor 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 anErrorobject. The following examples check ifpackage.jsonexists, 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.
datacan be a string or aBuffer.The
modeoption 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
optionsis a string, then it specifies the encoding:import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback);The
pathmay 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 otherfsoperation may lead to undefined behavior.See the POSIX
close(2)documentation for more detail.namespace close
- ): void;
Asynchronously copies
srctodest. By default,destis 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.modeis an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);@param srcsource filename to copy
@param destdestination filename of the copy operation
mode: number,): void;Asynchronously copies
srctodest. By default,destis 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.modeis an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; console.log('source.txt was copied to destination.txt'); } // destination.txt will be created or overwritten by default. copyFile('source.txt', 'destination.txt', callback); // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);@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.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Statsfor the file descriptor.See the POSIX
fstat(2)documentation for more detail.fd: number,): void;Invokes the callback with the
fs.Statsfor 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
lenbytes, only the firstlenbytes 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
lenbytes, it is extended, and the extended part is filled with null bytes ('\0'):If
lenis negative then0will 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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.Statsfor the symbolic link referred to by the path. The callback gets two arguments(err, stats)wherestatsis afs.Statsobject.lstat()is identical tostat(), except that ifpathis 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
recursiveistrue, the first directory path created,(err[, path]).pathcan still beundefinedwhenrecursiveistrue, if no directory was created (for instance, if it was previously created).The optional
optionsargument can be an integer specifyingmode(permission and sticky bits), or an object with amodeproperty and arecursiveproperty indicating whether parent directories should be created. Callingfs.mkdir()whenpathis a directory that exists results in an error only whenrecursiveis false. Ifrecursiveis false and the directory exists, anEEXISTerror 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
prefixto create a unique temporary directory. Due to platform inconsistencies, avoid trailingXcharacters inprefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailingXcharacters inprefixwith random characters.The created directory path is passed as a string to the callback's second parameter.
The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty 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 theprefixstring. For instance, given a directory/tmp, if the intention is to create a temporary directory within/tmp, theprefixmust 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,callback: (err: null | ErrnoException, folder: NonSharedBuffer) => 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.
@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 | NonSharedBuffer) => 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.
@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.modesets 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 systemflags``.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 systemflags``.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
encodingoption sets the encoding for thepathwhile 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
encodingoption sets the encoding for thepathwhile 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 anObjectwithbytesReadandbufferproperties.@param bufferThe buffer that the data will be written to.
@param offsetThe position in
bufferto write the data to.@param lengthThe number of bytes to read.
@param positionSpecifies where to begin reading from in the file. If
positionisnullor-1, data will be read from the current file position, and the file position will be updated. Ifpositionis 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.readfunction, this version takes an optionaloptionsobject. If not otherwise specified in anoptionsobject,bufferdefaults toBuffer.alloc(16384),offsetdefaults to0,lengthdefaults tobuffer.byteLength,- offsetas of Node 17.6.0positiondefaults tonullfd: 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 anObjectwithbytesReadandbufferproperties.@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 anObjectwithbytesReadandbufferproperties.@param bufferThe buffer that the data will be written to.
fd: number,callback: (err: null | ErrnoException, bytesRead: number, buffer: NonSharedBuffer) => 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 anObjectwithbytesReadandbufferproperties.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)wherefilesis an array of the names of the files in the directory excluding'.'and'..'.See the POSIX
readdir(3)documentation for more details.The optional
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the filenames passed to the callback. If theencodingis set to'buffer', the filenames returned will be passed asBufferobjects.If
options.withFileTypesis set totrue, thefilesarray will containfs.Direntobjects.options: 'buffer' | { encoding: 'buffer'; recursive: boolean; withFileTypes: false },callback: (err: null | ErrnoException, files: NonSharedBuffer[]) => 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.@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 },callback: (err: null | ErrnoException, files: string[] | NonSharedBuffer[]) => 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.@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: truethe result data will be an array of Dirent.options: { encoding: 'buffer'; recursive: boolean; withFileTypes: true },): 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 optionsMust include
withFileTypes: trueandencoding: 'buffer'.namespace readdir
- callback: (err: null | ErrnoException, data: NonSharedBuffer) => void): 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), wheredatais the contents of the file.If no encoding is specified, then the raw buffer is returned.
If
optionsis 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.readFileperforms.@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'.callback: (err: null | ErrnoException, data: string | NonSharedBuffer) => 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'.callback: (err: null | ErrnoException, data: NonSharedBuffer) => 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.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
optionsargument can be a string specifying an encoding, or an object with anencodingproperty specifying the character encoding to use for the link path passed to the callback. If theencodingis set to'buffer', the link path returned will be passed as aBufferobject.callback: (err: null | ErrnoException, linkString: NonSharedBuffer) => void): 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.callback: (err: null | ErrnoException, linkString: string | NonSharedBuffer) => void): 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: TBuffers,cb: (err: null | ErrnoException, bytesRead: number, buffers: TBuffers) => void): void;
Read from a file specified by
fdand write to an array ofArrayBufferViews usingreadv().positionis 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.bytesReadis how many bytes were read from the file.If this method is invoked as its
util.promisify()ed version, it returns a promise for anObjectwithbytesReadandbuffersproperties.fd: number,buffers: TBuffers,position: null | number,cb: (err: null | ErrnoException, bytesRead: number, buffers: TBuffers) => void): void;Read from a file specified by
fdand write to an array ofArrayBufferViews usingreadv().positionis 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.bytesReadis how many bytes were read from the file.If this method is invoked as its
util.promisify()ed version, it returns a promise for anObjectwithbytesReadandbuffersproperties.namespace readv
- ): void;
Asynchronously rename file at
oldPathto the pathname provided asnewPath. In the case thatnewPathalready 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
rmutility). No arguments other than a possible exception are given to the completion callback.): void;Asynchronously removes files and directories (modeled on the standard POSIX
rmutility). 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 anENOENTerror on Windows and anENOTDIRerror on POSIX.To get a behavior similar to the
rm -rfUnix 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 anENOENTerror on Windows and anENOTDIRerror on POSIX.To get a behavior similar to the
rm -rfUnix command, use rm with options{ recursive: true, force: true }.namespace rmdir
- ): void;
Asynchronous
stat(2). The callback gets two arguments(err, stats)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.Statsobject.In case of an error, the
err.codewill 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.jsThe 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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)wherestatsis anfs.StatFsobject.In case of an error, the
err.codewill 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
pathpointing totarget. No arguments other than a possible exception are given to the completion callback.See the POSIX
symlink(2)documentation for more details.The
typeargument is only available on Windows and ignored on other platforms. It can be set to'dir','file', or'junction'. If thetypeargument is not a string, Node.js will autodetecttargettype and use'file'or'dir'. If thetargetdoes not exist,'file'will be used. Windows junction points require the destination path to be absolute. When using'junction', thetargetargument 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
mewtwowhich points tomewin 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
atimeandmtimearguments follow these rules:- Values can be either numbers representing Unix epoch time in seconds,
Dates, or a numeric string like'123456789.0'. - If the value can not be converted to a number, or is
NaN,Infinity, or-Infinity, anErrorwill be thrown.
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
bufferto the file specified byfd.offsetdetermines the part of the buffer to be written, andlengthis an integer specifying the number of bytes to write.positionrefers 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)wherebytesWrittenspecifies how many bytes were written frombuffer.If this method is invoked as its
util.promisify()ed version, it returns a promise for anObjectwithbytesWrittenandbufferproperties.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
bufferto 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
bufferto 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
bufferto the file referenced by the supplied file descriptor.@param fdA file descriptor.
fd: number,buffer: TBuffer,callback: (err: null | ErrnoException, written: number, buffer: TBuffer) => void): void;Asynchronously writes
bufferto the file referenced by the supplied file descriptor.@param fdA file descriptor.
@param optionsAn object with the following properties:
offsetThe part of the buffer to be written. If not supplied, defaults to0.lengthThe number of bytes to write. If not supplied, defaults tobuffer.length - offset.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,position: undefined | null | number,encoding: undefined | null | BufferEncoding,callback: (err: null | ErrnoException, written: number, str: string) => void): void;Asynchronously writes
stringto 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
stringto 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
stringto 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
fileis a filename, asynchronously writes data to the file, replacing the file if it already exists.datacan be a string or a buffer.When
fileis a file descriptor, the behavior is similar to callingfs.write()directly (which is recommended). See the notes below on using a file descriptor.The
encodingoption is ignored ifdatais a buffer.The
modeoption 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
optionsis 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.writeFileis a convenience method that performs multiplewritecalls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.It is possible to use an
AbortSignalto 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.writeFileperforms.@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: TBuffers,cb: (err: null | ErrnoException, bytesWritten: number, buffers: TBuffers) => void): void;
Write an array of
ArrayBufferViews to the file specified byfdusingwritev().positionis 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.bytesWrittenis how many bytes were written frombuffers.If this method is
util.promisify()ed, it returns a promise for anObjectwithbytesWrittenandbuffersproperties.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: TBuffers,position: null | number,cb: (err: null | ErrnoException, bytesWritten: number, buffers: TBuffers) => void): void;Write an array of
ArrayBufferViews to the file specified byfdusingwritev().positionis 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.bytesWrittenis how many bytes were written frombuffers.If this method is
util.promisify()ed, it returns a promise for anObjectwithbytesWrittenandbuffersproperties.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
- filter?: (source: string, destination: string) => boolean | Promise<boolean>
Function to filter copied files/directories. Return
trueto copy the item,falseto ignore it. - 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
errorOnExistoption to change this behavior.
interface CopySyncOptions
- filter?: (source: string, destination: string) => boolean
Function to filter copied files/directories. Return
trueto copy the item,falseto ignore it. - 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
errorOnExistoption to change this behavior.
interface DisposableTempDir
The same as
remove.A function which removes the created directory.
interface FSWatcher
The
EventEmitterclass is defined and exposed by thenode:eventsmodule:import { EventEmitter } from 'node:events';All
EventEmitters 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',listener: (eventType: string, filename: string | NonSharedBuffer) => void): 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.FSWatcherobject 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
trueif the event had listeners,falseotherwise.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
Symbols.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
EventEmitterwhich 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. Iflisteneris 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
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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',listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;Adds the
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventName. The next timeeventNameis 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',listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;Adds a one-time
listenerfunction for the event namedeventName. The next timeeventNameis 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
listenerfunction for the event namedeventName. The next timeeventNameis 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
listenerfunction for the event namedeventName. The next timeeventNameis 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
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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',listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;Adds the
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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',listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;Adds a one-time
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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.FSWatcheris active. Callingwatcher.ref()multiple times will have no effect.By default, all
fs.FSWatcherobjects 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
EventEmitterinstance 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
listenerfrom 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: // ABecause 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
EventEmitters will print a warning if more than10listeners 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 specificEventEmitterinstance. 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.FSWatcherobject 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.FSWatcherobject's callback is invoked. Callingwatcher.unref()multiple times will have no effect.
interface GlobOptions
- exclude?: readonly string[] | (fileName: string | Dirent<string>) => boolean
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return
trueto exclude the item,falseto include it. If a string array is provided, each string should be a glob pattern that specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are not supported.
interface GlobOptionsWithFileTypes
- exclude?: readonly string[] | (fileName: Dirent) => boolean
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return
trueto exclude the item,falseto include it. If a string array is provided, each string should be a glob pattern that specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are not supported.
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
trueto exclude the item,falseto include it. If a string array is provided, each string should be a glob pattern that specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are not supported.
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 ReadOptions
interface ReadOptionsWithBuffer<T extends NodeJS.ArrayBufferView>
interface ReadVResult<T extends readonly NodeJS.ArrayBufferView[] = NodeJS.ArrayBufferView[]>
interface RmDirOptions
- maxRetries?: number
If an
EBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERMerror is encountered, Node.js will retry the operation with a linear backoff wait ofretryDelayms longer on each try. This option represents the number of retries. This option is ignored if therecursiveoption is nottrue. - retryDelay?: number
The amount of time in milliseconds to wait between retries. This option is ignored if the
recursiveoption is nottrue.
interface RmOptions
- maxRetries?: number
If an
EBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERMerror is encountered, Node.js will retry the operation with a linear backoff wait ofretryDelayms longer on each try. This option represents the number of retries. This option is ignored if therecursiveoption 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
recursiveoption 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
trueif the event had listeners,falseotherwise.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
Symbols.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
EventEmitterwhich 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. Iflisteneris 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
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventName. The next timeeventNameis 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
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing 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
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis 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.StatWatcheris active. Callingwatcher.ref()multiple times will have no effect.By default, all
fs.StatWatcherobjects 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
EventEmitterinstance 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
listenerfrom 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: // ABecause 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
EventEmitters will print a warning if more than10listeners 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 specificEventEmitterinstance. 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.StatWatcherobject 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.StatWatcherobject's callback is invoked. Callingwatcher.unref()multiple times will have no effect.
interface Utf8StreamOptions
- contentMode?: 'utf8' | 'buffer'
Which type of data you can send to the write function, supported values are
'utf8'or'buffer'. - fs?: object
An object that has the same API as the
fsmodule, useful for mocking, testing, or customizing the behavior of the stream. - maxLength?: number
The maximum length of the internal buffer. If a write operation would cause the buffer to exceed
maxLength, the data written is dropped and a drop event is emitted with the dropped data - minLength?: number
The minimum length of the internal buffer that is required to be full before flushing.
- retryEAGAIN?: (err: null | Error, writeBufferLen: number, remainingBufferLen: number) => boolean
A function that will be called when
write(),writeSync(), orflushSync()encounters anEAGAINorEBUSYerror. If the return value istruethe operation will be retried, otherwise it will bubble the error. Theerris the error that caused this function to be called,writeBufferLenis the length of the buffer that was written, andremainingBufferLenis the length of the remaining buffer that the stream did not try to write.
interface WatchFileOptions
Watch for changes on
filename. The callbacklistenerwill be called each time the file is accessed.The
optionsargument may be omitted. If provided, it should be an object. Theoptionsobject may contain a boolean namedpersistentthat indicates whether the process should continue to run as long as files are being watched. Theoptionsobject may specify anintervalproperty indicating how often the target should be polled in milliseconds.The
listenergets 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 thebigintoption istrue, the numeric values in these objects are specified asBigInts.To be notified when the file was modified, not just accessed, it is necessary to compare
curr.mtimeMsandprev.mtimeMs.When an
fs.watchFileoperation results in anENOENTerror, 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.watchFileandfs.unwatchFile.fs.watchshould be used instead offs.watchFileandfs.unwatchFilewhen possible.When a file being watched by
fs.watchFile()disappears and reappears, then the contents ofpreviousin the second callback event (the file's reappearance) will be the same as the contents ofpreviousin 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
AbortControllercan be used to cancel an asynchronous action.
interface WatchOptionsWithBufferEncoding
- signal?: AbortSignal
When provided the corresponding
AbortControllercan be used to cancel an asynchronous action.
interface WatchOptionsWithStringEncoding
- signal?: AbortSignal
When provided the corresponding
AbortControllercan be used to cancel an asynchronous action.
interface WriteOptions
interface WriteVResult<T extends readonly NodeJS.ArrayBufferView[] = NodeJS.ArrayBufferView[]>
- 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