Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
Search the reference...
/
Node.js module
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.
Fully implemented. 92% of Node.js's test suite passes.
namespace constantsconst COPYFILE_EXCL: numberConstant 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.
Asynchronously computes the canonical pathname by resolving ., .., and symbolic links.
A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.
This function behaves like realpath(3), with some exceptions:
No case conversion is performed on case-insensitive file systems.The maximum number of symbolic links is platform-independent and generally (much) higher than what the native realpath(3) implementation supports.The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
If path resolves to a socket or a pipe, the function will return a system dependent name for that object.
Asynchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of this API: realpath.
Synchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Synchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
A class representing a directory stream.
Created by opendir, opendirSync, or fsPromises.opendir().
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
When using the async iterator, the fs.Dir object will be automatically closed after the iterator exits.
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 returns undefined.
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.
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 an fs.Dirent.
A promise is returned that will be fulfilled with an fs.Dirent, or null if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
containing {fs.Dirent|null}
Asynchronously read the next directory entry via readdir(3) as an fs.Dirent.
A promise is returned that will be fulfilled with an fs.Dirent, or null if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
containing {fs.Dirent|null}
Synchronously read the next directory entry as an fs.Dirent. See the POSIX readdir(3) documentation for more detail.
If there are no more directory entries to read, null will be returned.
Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an fs.Dir. The directory entry is a combination of the file name and file type pairs.
Additionally, when readdir or readdirSync is called with the withFileTypes option set to true, the resulting array is filled with fs.Dirent objects, rather than strings or Buffer s.
The file name that this fs.Dirent object refers to. The type of this value is determined by the options.encoding passed to readdir or readdirSync.
The path to the parent directory of the file this fs.Dirent object refers to.
Returns true if the fs.Dirent object describes a block device.
Returns true if the fs.Dirent object describes a character device.
Returns true if the fs.Dirent object describes a file system directory.
Returns true if the fs.Dirent object describes a first-in-first-out (FIFO) pipe.
Returns true if the fs.Dirent object describes a regular file.
Returns true if the fs.Dirent object describes a socket.
Returns true if the fs.Dirent object describes a symbolic link.
Instances of fs.ReadStream cannot be constructed directly. They are created and returned using the fs.createReadStream() function.
The number of bytes that have been read so far.
Is true after 'close' has been emitted.
Is true after readable.destroy() has been called.
Returns error if the stream has been destroyed with an error.
The path to the file the stream is reading from as specified in the first argument to fs.createReadStream(). If path is passed as a string, thenreadStream.path will be a string. If path is passed as a Buffer, thenreadStream.path will be a Buffer. If fd is specified, thenreadStream.path will be undefined.
This property is true if the underlying file has not been opened yet, i.e. before the 'ready' event is emitted.
Is true if it is safe to call read, which means the stream has not been destroyed or emitted 'error' or 'end'.
Returns whether the stream was destroyed or errored before emitting 'end'.
Returns whether 'data' has been emitted.
Getter for the property encoding of a given Readable stream. The encoding property can be set using the setEncoding method.
Becomes true when 'end' event is emitted.
This property reflects the current state of a Readable stream as described in the Three states section.
Returns the value of highWaterMark passed when creating this Readable.
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.
Getter for the property objectMode of a given Readable stream.
Calls readable.destroy() with an AbortError and returns a promise that fulfills when the stream is finished.
AsyncIterator to fully consume the stream.
The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
[captureRejectionSymbol](err, event, ...args) {
console.log('rejection happened for', event, 'with', err, ...args);
this.destroy(err);
}
destroy(err) {
// Tear the resource down here.
}
}
Alias for emitter.on(eventName, listener).
import { Readable } from 'node:stream';
async function* splitToWords(source) {
for await (const chunk of source) {
const words = String(chunk).split(' ');
for (const word of words) {
yield word;
}
}
}
const wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords);
const words = await wordsStream.toArray();
console.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']
readable.compose(s) is equivalent to stream.compose(readable, s).
This method also allows for an AbortSignal to be provided, which will destroy the composed stream when aborted.
See stream.compose(...streams) for more information.
a stream composed with the stream stream.
Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the readable stream will release any internal resources and subsequent calls to push() 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().
Error which will be passed as payload in 'error' event
This method returns a new stream with the first limit chunks dropped from the start.
the number of chunks to drop from the readable.
a stream with limit chunks dropped from the start.
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Returns an array listing the events for which the emitter has registered listeners.
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) ]
This method is similar to Array.prototype.every and calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunk awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.
a function to call on each chunk of the stream. Async or not.
a promise evaluating to true if fn returned a truthy value for every one of the chunks.
This method allows filtering the stream. For each chunk in the stream the fn function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the fn function returns a promise - that promise will be awaited.
a function to filter chunks from the stream. Async or not.
a stream filtered with the predicate fn.
This method is similar to Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
a promise evaluating to the first chunk for which fn evaluated with a truthy value, or undefined if no element was found.
This method is similar to Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
a promise evaluating to the first chunk for which fn evaluated with a truthy value, or undefined if no element was found.
This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.
It is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.
a function to map over every chunk in the stream. May be async. May be a stream or generator.
a stream flat-mapped with the function fn.
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...of loops in that it can optionally process chunks concurrently. In addition, a forEach iteration can only be stopped by having passed a signal option and aborting the related AbortController while for await...of can be stopped with break or return. In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it uses the readable event in the underlying machinary and can limit the number of concurrent fn calls.
a function to call on each chunk of the stream. Async or not.
a promise for when the stream has finished.
Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.
The readable.isPaused() method returns the current operating state of the Readable. This is used primarily by the mechanism that underlies the readable.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
The iterator created by this method gives users the option to cancel the destruction of the stream if the for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler 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] ]
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.
a function to map over every chunk in the stream. Async or not.
a stream mapped with the function fn.
Alias for emitter.removeListener().
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The 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.
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback 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');
The readable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.
The optional size argument specifies a specific number of bytes to read. If size bytes are not available to be read, null will be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.
If the size argument is not specified, all of the data contained in the internal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams operating in paused mode. In flowing mode, readable.read() is called automatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
Each call to readable.read() returns a chunk of data, or null. The chunks are not concatenated. A while loop is necessary to consume all data currently in the buffer. When reading a large file .read() may return null, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new 'readable' event will be emitted when there is more data in the buffer. Finally the 'end' event will be emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary to collect chunks across multiple 'readable' events:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
A Readable stream in object mode will always return a single item from a call to readable.read(size), regardless of the value of the size argument.
If the readable.read() method returns a chunk of data, a 'data' event will also be emitted.
Calling read after the 'end' event has been emitted will return null. No runtime error will be raised.
Optional argument to specify how much data to read.
This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
a promise for the final value of the reduction.
This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
the initial value to use in the reduction.
a promise for the final value of the reduction.
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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 paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
The readable.resume() method has no effect if there is a 'readable' event listener.
The readable.setEncoding() method sets the character encoding for data read from the Readable stream.
By default, no encoding is assigned and stream data will be returned as Buffer objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects. For instance, calling readable.setEncoding('utf8') will cause the output data to be interpreted as UTF-8 data, and passed as strings. Calling readable.setEncoding('hex') will cause the data to be encoded in hexadecimal string format.
The Readable stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
The encoding to use.
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
This method is similar to Array.prototype.some and calls fn on each chunk in the stream until the awaited return value is true (or any truthy value). Once an fn call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.
a function to call on each chunk of the stream. Async or not.
a promise evaluating to true if fn returned a truthy value for at least one of the chunks.
This method returns a new stream with the first limit chunks.
the number of chunks to take from the readable.
a stream with limit chunks taken.
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.
a promise containing an array with the contents of the stream.
The readable.unpipe() method detaches a Writable stream previously attached using the pipe method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then the method does nothing.
import fs from 'node:fs';
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
Optional specific stream to unpipe
Passing chunk as null signals the end of the stream (EOF) and behaves the same as readable.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 a Transform stream instead. See the API for stream implementers section for more information.
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
import { StringDecoder } from 'node:string_decoder';
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.includes('\n\n')) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
return;
}
// Still reading the header.
header += str;
}
}
}
Unlike push, stream.unshift(chunk) will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if readable.unshift() is called during a read (i.e. from within a _read implementation on a custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately, however it is best to simply avoid calling readable.unshift() while in the process of performing a read.
Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray}, {DataView} or null. For object mode streams, chunk may be any JavaScript value.
Encoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.
Prior to Node.js 0.10, streams did not implement the entire node:stream module API as it is currently defined. (See Compatibility for more information.)
When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, the readable.wrap() method can be used to create a Readable stream that uses the old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been provided as a convenience for interacting with older Node.js applications and libraries.
import { OldReader } from './old-api-module.js';
import { Readable } from 'node:stream';
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
An "old style" readable stream
A utility method for creating Readable Streams out of iterators.
Object implementing the Symbol.asyncIterator or Symbol.iterator iterable protocol. Emits an 'error' event if a null value is passed.
Options provided to new stream.Readable([options]). By default, Readable.from() will set options.objectMode to true, unless this is explicitly opted out by setting options.objectMode to false.
A utility method for creating a Readable from a web ReadableStream.
Returns whether the stream has been read from or cancelled.
A utility method for creating a web ReadableStream from a Readable.
A fs.Stats object provides information about a file.
Objects returned from stat, lstat, fstat, and their synchronous counterparts are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of number, and the object will contain additional nanosecond-precision properties suffixed with Ns. Stat objects are not to be created directly using the new keyword.
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
bigint version:
BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
Provides information about a mounted file system.
Objects returned from statfs and its synchronous counterpart are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of number.
StatFs {
type: 1397114950,
bsize: 4096,
blocks: 121938943,
bfree: 61058895,
bavail: 61058895,
files: 999,
ffree: 1000000
}
bigint version:
StatFs {
type: 1397114950n,
bsize: 4096n,
blocks: 121938943n,
bfree: 61058895n,
bavail: 61058895n,
files: 999n,
ffree: 1000000n
}
Available blocks for unprivileged users
Free blocks in file system.
Total data blocks in file system.
Optimal transfer block size.
Free file nodes in file system.
Total file nodes in file system.
Type of file system.
An optimized UTF-8 stream writer that allows for flushing all the internal buffering on demand. It handles EAGAIN errors correctly, allowing for customization, for example, by dropping content if the disk is busy.
Whether the stream is appending to the file or truncating it.
The type of data that can be written to the stream. Supported values are 'utf8' or 'buffer'.
The file descriptor that is being written to.
The file that is being written to.
Whether the stream is performing a fs.fsyncSync() after every write operation.
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.
The minimum length of the internal buffer that is required to be full before flushing.
Whether the stream should ensure that the directory for the dest file exists. If true, it will create the directory if it does not exist.
The mode of the file that is being written to.
The number of milliseconds between flushes. If set to 0, no periodic flushes will be performed.
Whether the stream is writing synchronously or asynchronously.
Whether the stream is currently writing data to the file.
The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
[captureRejectionSymbol](err, event, ...args) {
console.log('rejection happened for', event, 'with', err, ...args);
this.destroy(err);
}
destroy(err) {
// Tear the resource down here.
}
}
Calls utf8Stream.destroy().
Alias for emitter.on(eventName, listener).
Alias for emitter.on(eventName, listener).
Close the stream immediately, without flushing the internal buffer.
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Close the stream gracefully, flushing the internal buffer before closing.
Returns an array listing the events for which the emitter has registered listeners.
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) ]
Writes the current buffer to the file if a write was not in progress. Do nothing if minLength is zero or if it is already writing.
Flushes the buffered data synchronously. This is a costly operation.
Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler function
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler 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] ]
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] ]
Alias for emitter.removeListener().
Alias for emitter.removeListener().
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback 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');
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');
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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.
Reopen the file in place, useful for log rotation.
A path to a file to be written to (mode controlled by the append option).
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
When the options.contentMode is set to 'utf8' when the stream is created, the data argument must be a string. If the contentMode is set to 'buffer', the data argument must be a Buffer.
The data to write.
Instances of fs.WriteStream cannot be constructed directly. They are created and returned using the fs.createWriteStream() function.
The number of bytes written so far. Does not include data that is still queued for writing.
Is true after 'close' has been emitted.
Is true after writable.destroy() has been called.
Returns error if the stream has been destroyed with an error.
The path to the file the stream is writing to as specified in the first argument to createWriteStream. If path is passed as a string, thenwriteStream.path will be a string. If path is passed as a Buffer, thenwriteStream.path will be a Buffer.
This property is true if the underlying file has not been opened yet, i.e. before the 'ready' event is emitted.
Is true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.
Returns whether the stream was destroyed or errored before emitting 'finish'.
Number of times writable.uncork() needs to be called in order to fully uncork the stream.
Is true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.
Is set to true immediately before the 'finish' event is emitted.
Return the value of highWaterMark passed when creating this Writable.
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.
Is true if the stream's buffer has been full and stream will emit 'drain'.
Getter for the property objectMode of a given Writable stream.
Calls writable.destroy() with an AbortError and returns a promise that fulfills when the stream is finished.
The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
[captureRejectionSymbol](err, event, ...args) {
console.log('rejection happened for', event, 'with', err, ...args);
this.destroy(err);
}
destroy(err) {
// Tear the resource down here.
}
}
Alias for emitter.on(eventName, listener).
Closes writeStream. Optionally accepts a callback that will be executed once the writeStreamis closed.
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 until writable.uncork() is called, which will pass them all to writable._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 of writable.cork() without implementing writable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the writable stream has ended and subsequent calls to write() or end() will result in an ERR_STREAM_DESTROYED error. This is a destructive and immediate way to destroy a stream. Previous calls to write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. Use end() 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().
Optional, an error to emit with 'error' event.
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.
Calling the write method after calling end will raise an error.
// Write 'hello, ' and then end with 'world!'.
import fs from 'node:fs';
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
Callback for when the stream is finished.
Signals that no more data will be written, with one final chunk of data.
Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.
Callback for when the stream is finished.
Signals that no more data will be written, with one final chunk of data.
Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.
The encoding if chunk is a string
Callback for when the stream is finished.
Returns an array listing the events for which the emitter has registered listeners.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler 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] ]
Alias for emitter.removeListener().
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback 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');
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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 writable.setDefaultEncoding() method sets the default encoding for a Writable stream.
The new default encoding
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) 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() and writable.uncork() to manage the buffering of writes to a stream, defer calls to writable.uncork() using process.nextTick(). Doing so allows batching of all writable.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 to writable.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().
The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.
The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() 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 the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.
If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
A Writable stream in object mode will always ignore the encoding argument.
Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.
Callback for when this chunk of data is flushed.
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
Writes data to the stream, with an explicit encoding for string data.
Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.
The encoding, if chunk is a string.
Callback for when this chunk of data is flushed.
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
A utility method for creating a Writable from a web WritableStream.
A utility method for creating a web WritableStream from a Writable.
Tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.
The final argument, callback, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an Error object. The following examples check if package.json exists, and if it is readable or writable.
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile(), or fs.writeFile(). Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.
write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The fs.access() function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.
Asynchronously tests a user's permissions for the file specified by path.
A path to a file or directory. If a URL is provided, it must use the file: protocol.
Synchronously tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.
If any of the accessibility checks fail, an Error will be thrown. Otherwise, the method will return undefined.
import { accessSync, constants } from 'node:fs';
try {
accessSync('etc/passwd', constants.R_OK | constants.W_OK);
console.log('can read/write');
} catch (err) {
console.error('no access!');
}
Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
filename or file descriptor
Asynchronously append data to a file, creating the file if it does not exist.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
Synchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFileSync } from 'node:fs';
try {
appendFileSync('message.txt', 'data to append');
console.log('The "data to append" was appended to file!');
} catch (err) {
// Handle the error
}
If options is a string, then it specifies the encoding:
import { appendFileSync } from 'node:fs';
appendFileSync('message.txt', 'data to append', 'utf8');
The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.
import { openSync, closeSync, appendFileSync } from 'node:fs';
let fd;
try {
fd = openSync('message.txt', 'a');
appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
// Handle the error
} finally {
if (fd !== undefined)
closeSync(fd);
}
filename or file descriptor
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!');
});
For detailed information, see the documentation of the asynchronous version of this API: chmod.
See the POSIX chmod(2) documentation for more detail.
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.
Synchronously changes owner and group of a file. Returns undefined. This is the synchronous version of chown.
See the POSIX chown(2) documentation for more detail.
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 other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
Closes the file descriptor. Returns undefined.
Calling fs.closeSync() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
source filename to copy
destination filename of the copy operation
Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
source filename to copy
destination filename of the copy operation
modifiers for copy operation.
Synchronously copies src to dest. By default, dest is overwritten if it already exists. Returns undefined. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.import { copyFileSync, constants } from 'node:fs';
// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
source filename to copy
destination filename of the copy operation
modifiers for copy operation.
Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.
When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.
Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.
When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.
Synchronously copies the entire directory structure from src to dest, including subdirectories and files.
When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.
options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is omitted or undefined, fs.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by Buffer.
If fd is specified, ReadStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.
If fd points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.
By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option, an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is also required.
import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.
mode sets the file mode (permission and sticky bits), but only if the file was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });
If options is a string, then it specifies the encoding.
options may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags option to be set to r+ rather than the default w. The encoding can be any one of those accepted by Buffer.
If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.
By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option it is possible to override the corresponding fs implementations for open, write, writev, and close. Overriding write() without writev() can reduce performance as some optimizations (_writev()) will be disabled. When providing the fs option, overrides for at least one of write and writev are required. If no fd option is supplied, an override for open is also required. If autoClose is true, an override for close is also required.
Like fs.ReadStream, if fd is specified, fs.WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.
If options is a string, then it specifies the encoding.
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.
Sets the permissions on the file. Returns undefined.
See the POSIX fchmod(2) documentation for more detail.
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.
Sets the owner of the file. Returns undefined.
See the POSIX fchown(2) documentation for more detail.
The file's new owner's user id.
The file's new group's group id.
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback.
Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns undefined.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Retrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Retrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Retrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
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.
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. Returns undefined.
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
See the POSIX ftruncate(2) documentation for more detail.
If the file referred to by the file descriptor was larger than len bytes, only the first len bytes will be retained in the file.
For example, the following program retains only the first four bytes of the file:
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
});
If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):
If len is negative then 0 will be used.
Asynchronous ftruncate(2) - Truncate a file to a specified length.
A file descriptor.
Truncates the file descriptor. Returns undefined.
For detailed information, see the documentation of the asynchronous version of this API: ftruncate.
Change the file system timestamps of the object referenced by the supplied file descriptor. See utimes.
Synchronous version of futimes. Returns undefined.
Retrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
Retrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
Retrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
Retrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
import { globSync } from 'node:fs';
console.log(globSync('*.js'));
paths of files that match the pattern.
import { globSync } from 'node:fs';
console.log(globSync('*.js'));
paths of files that match the pattern.
import { globSync } from 'node:fs';
console.log(globSync('*.js'));
paths of files that match the pattern.
import { globSync } from 'node:fs';
console.log(globSync('*.js'));
paths of files that match the pattern.
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.
Set the owner for the path. Returns undefined.
See the POSIX lchown(2) documentation for more details.
The file's new owner's user id.
The file's new group's group id.
Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.
Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. Returns undefined.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
A path to a file. If a URL is provided, it must use the file: protocol.
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.
Change the file system timestamps of the symbolic link referenced by path. Returns undefined, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of lutimes.
Asynchronously creates a directory.
The callback is given a possible exception and, if recursive is true, the first directory path created, (err[, path]).path can still be undefined when recursive is true, if no directory was created (for instance, if it was previously created).
The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false. If recursive is false and the directory exists, an EEXIST error occurs.
import { mkdir } from 'node:fs';
// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
On Windows, using fs.mkdir() on the root directory even with recursion will result in an error:
import { mkdir } from 'node:fs';
mkdir('/', { recursive: true }, (err) => {
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
See the POSIX mkdir(2) documentation for more details.
Asynchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.
Asynchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.
Asynchronous mkdir(2) - create a directory with a mode of 0o777.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronously creates a directory. Returns undefined, or if recursive is true, the first directory path created. This is the synchronous version of mkdir.
See the POSIX mkdir(2) documentation for more details.
Synchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.
Synchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.
Creates a unique temporary directory.
Generates six random characters to be appended behind a required prefix to create a unique temporary directory. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.
The created directory path is passed as a string to the callback's second parameter.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
The fs.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within/tmp, the prefixmust end with a trailing platform-specific path separator (import { sep } from 'node:path').
import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';
// The parent directory for the new temporary directory
const tmpDir = tmpdir();
// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmpabc123`.
// A new temporary directory is created at the file system root
// rather than *within* the /tmp directory.
});
// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmp/abc123`.
// A new temporary directory is created within
// the /tmp directory.
});
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
Returns a disposable object whose path property 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 a remove() method which will perform the same task.
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 using syntax.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.
Returns the created directory path.
For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.
Synchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Synchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous file open. See the POSIX open(2) documentation for more details.
mode sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see chmod.
The callback gets two arguments (err, fd).
Some characters ( : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.
Functions based on fs.open() exhibit this behavior as well:fs.writeFile(), fs.readFile(), etc.
See support of file system flags``.
Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.
A path to a file. If a URL is provided, it must use the file: protocol.
See support of file system flags``.
Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.
A path to a file. If a URL is provided, it must use the file: protocol.
Returns a Blob whose data is backed by the given file.
The file must not be modified after the Blob is created. Any modifications will cause reading the Blob data to fail with a DOMException error. Synchronous stat operations on the file when the Blob is created, and before each read in order to detect whether the file data has been modified on disk.
import { openAsBlob } from 'node:fs';
const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();
Asynchronously open a directory. See the POSIX opendir(3) documentation for more details.
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
Asynchronously open a directory. See the POSIX opendir(3) documentation for more details.
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
Synchronously open a directory. See opendir(3).
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
Returns an integer representing the file descriptor.
For detailed information, see the documentation of the asynchronous version of this API: open.
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 an Object with bytesRead and buffer properties.
The buffer that the data will be written to.
The position in buffer to write the data to.
The number of bytes to read.
Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.
Similar to the above fs.read function, this version takes an optional options object. If not otherwise specified in an options object, buffer defaults to Buffer.alloc(16384), offset defaults to 0, length defaults to buffer.byteLength, - offset as of Node 17.6.0 position defaults to null
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 an Object with bytesRead and buffer properties.
The buffer that the data will be written to.
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 an Object with bytesRead and buffer properties.
The buffer that the data will be written to.
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 an Object with bytesRead and buffer properties.
Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames passed to the callback. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the files array will contain fs.Dirent objects.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
If called with withFileTypes: true the result data will be an array of Dirent.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Must include withFileTypes: true and encoding: 'buffer'.
Reads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects.
Synchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
The 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.
A path to a file. If a URL is provided, it must use the file: protocol.
The 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.
A path to a file. If a URL is provided, it must use the file: protocol.
If called with withFileTypes: true the result data will be an array of Dirent.
Synchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Must include withFileTypes: true and encoding: 'buffer'.
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), where data is the contents of the file.
If no encoding is specified, then the raw buffer is returned.
If options is a string, then it specifies the encoding:
import { readFile } from 'node:fs';
readFile('/etc/passwd', 'utf8', callback);
When the path is a directory, the behavior of fs.readFile() and readFileSync is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.
import { readFile } from 'node:fs';
// macOS, Linux, and Windows
readFile('', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read ]
});
// FreeBSD
readFile('', (err, data) => {
// => null,
});
It is possible to abort an ongoing request using an AbortSignal. If a request is aborted the callback is called with an AbortError:
import { readFile } from 'node:fs';
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
// ...
});
// When you want to abort the request
controller.abort();
The fs.readFile() function buffers the entire file. To minimize memory costs, when possible prefer streaming via fs.createReadStream().
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.
filename or file descriptor
Asynchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
Asynchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
Asynchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Returns the contents of the path.
For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
Similar to readFile, when the path is a directory, the behavior of fs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('');
// => [Error: EISDIR: illegal operation on a directory, read ]
// FreeBSD
readFileSync(''); // =>
filename or file descriptor
Synchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
Synchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
Reads the contents of the symbolic link referred to by path. The callback gets two arguments (err, linkString).
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path passed to the callback. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
Returns the symbolic link's string value.
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object.
Synchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Synchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Returns the number of bytesRead.
For detailed information, see the documentation of the asynchronous version of this API: read.
Similar to the above fs.readSync function, this version takes an optional options object. If no options object is specified, it will default with the above values.
Read from a file specified by fd and write to an array of ArrayBufferViews using readv().
position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.
The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffers properties.
Read from a file specified by fd and write to an array of ArrayBufferViews using readv().
position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.
The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffers properties.
For detailed information, see the documentation of the asynchronous version of this API: readv.
The number of bytes read.
Asynchronously computes the canonical pathname by resolving ., .., and symbolic links.
A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.
This function behaves like realpath(3), with some exceptions:
No case conversion is performed on case-insensitive file systems.The maximum number of symbolic links is platform-independent and generally (much) higher than what the native realpath(3) implementation supports.The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
If path resolves to a socket or a pipe, the function will return a system dependent name for that object.
Asynchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of this API: realpath.
Synchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Synchronous realpath(3) - return the canonicalized absolute pathname.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronously rename file at oldPath to the pathname provided as newPath. In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.
See also: rename(2).
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
Renames the file from oldPath to newPath. Returns undefined.
See the POSIX rename(2) documentation for more details.
Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.
Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.
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 an ENOENT error on Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use rm with options { recursive: true, force: true }.
Synchronous rmdir(2). Returns undefined.
Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use rmSync with options { recursive: true, force: true }.
Synchronously removes files and directories (modeled on the standard POSIX rm utility). Returns undefined.
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A 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 contains path.
In case of an error, the err.code will be one of Common System Errors.
A 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 contains path.
In case of an error, the err.code will be one of Common System Errors.
A 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 contains path.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Synchronous stat(2) - Get file status.
A path to a file. If a URL is provided, it must use the file: protocol.
Creates the link called path pointing to target. No arguments other than a possible exception are given to the completion callback.
See the POSIX symlink(2) documentation for more details.
The type argument is only available on Windows and ignored on other platforms. It can be set to 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', thetarget argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.
Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs';
symlink('./mew', './mewtwo', callback);
The above example creates a symbolic link mewtwo which points to mew in the same directory:
tree .
. ├── mew └── mewtwo -> ./mew
Asynchronous symlink(2) - Create a new symbolic link to an existing file.
A path to an existing file. If a URL is provided, it must use the file: protocol.
A path to the new symlink. If a URL is provided, it must use the file: protocol.
Returns undefined.
For detailed information, see the documentation of the asynchronous version of this API: symlink.
Asynchronous truncate(2) - Truncate a file to a specified length.
A path to a file. If a URL is provided, it must use the file: protocol.
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.
Synchronous unlink(2). Returns undefined.
Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of filename.
Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.
Using watch is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.
Optional, a listener previously attached using fs.watchFile()
Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of filename.
Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.
Using watch is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.
Optional, a listener previously attached using fs.watchFile()
Change the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
Values can be either numbers representing Unix epoch time 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, an Error will be thrown.Returns undefined.
For detailed information, see the documentation of the asynchronous version of this API: utimes.
Watch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
Watch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
Watch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
Watch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
Watch for changes on filename. The callback listener will be called each time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).
This happens when:
the file is deleted, followed by a restorethe file is renamed and then renamed a second time back to its original nameWatch for changes on filename. The callback listener will be called each time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).
This happens when:
the file is deleted, followed by a restorethe file is renamed and then renamed a second time back to its original nameWatch for changes on filename. The callback listener will be called each time the file is accessed.
A path to a file or directory. If a URL is provided, it must use the file: protocol.
Write buffer to the file specified by fd.
offset determines the part of the buffer to be written, and length is an integer specifying the number of bytes to write.
position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position. See pwrite(2).
The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesWritten and buffer properties.
It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
The part of the buffer to be written. If not supplied, defaults to 0.
The number of bytes to write. If not supplied, defaults to buffer.length - offset.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
The part of the buffer to be written. If not supplied, defaults to 0.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
An object with the following properties:
offset The part of the buffer to be written. If not supplied, defaults to 0.length The number of bytes to write. If not supplied, defaults to buffer.length - offset.position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.Asynchronously writes string to the file referenced by the supplied file descriptor.
A file descriptor.
A string to write.
The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
The expected string encoding.
Asynchronously writes string to the file referenced by the supplied file descriptor.
A file descriptor.
A string to write.
The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
Asynchronously writes string to the file referenced by the supplied file descriptor.
A file descriptor.
A string to write.
When file is a filename, asynchronously writes data to the file, replacing the file if it already exists. data can be a string or a buffer.
When file is a file descriptor, the behavior is similar to calling fs.write() directly (which is recommended). See the notes below on using a file descriptor.
The encoding option is ignored if data is a buffer.
The mode option only affects the newly created file. See open for more details.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
If options is a string, then it specifies the encoding:
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.
Similarly to fs.readFile - fs.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.
It is possible to use an AbortSignal to cancel an fs.writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
// When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs.
filename or file descriptor
Asynchronously writes data to a file, replacing the file if it already exists.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
Returns undefined.
The mode option only affects the newly created file. See open for more details.
For detailed information, see the documentation of the asynchronous version of this API: writeFile.
filename or file descriptor
For detailed information, see the documentation of the asynchronous version of this API: write.
The number of bytes written.
Synchronously writes string to the file referenced by the supplied file descriptor, returning the number of bytes written.
A file descriptor.
A string to write.
The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
The expected string encoding.
Write an array of ArrayBufferViews to the file specified by fd using writev().
position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.
The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
Write an array of ArrayBufferViews to the file specified by fd using writev().
position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.
The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
For detailed information, see the documentation of the asynchronous version of this API: writev.
The number of bytes written.
Tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.
The final argument, callback, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an Error object. The following examples check if package.json exists, and if it is readable or writable.
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile(), or fs.writeFile(). Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.
write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The fs.access() function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.
Asynchronously tests a user's permissions for the file specified by path.
A path to a file or directory. If a URL is provided, it must use the file: protocol.
Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
filename or file descriptor
Asynchronously append data to a file, creating the file if it does not exist.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
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!');
});
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.
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 other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
source filename to copy
destination filename of the copy operation
Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
source filename to copy
destination filename of the copy operation
modifiers for copy operation.
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.
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.
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.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Invokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.
Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
See the POSIX ftruncate(2) documentation for more detail.
If the file referred to by the file descriptor was larger than len bytes, only the first len bytes will be retained in the file.
For example, the following program retains only the first four bytes of the file:
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
});
If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):
If len is negative then 0 will be used.
Asynchronous ftruncate(2) - Truncate a file to a specified length.
A file descriptor.
Change the file system timestamps of the object referenced by the supplied file descriptor. See utimes.
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.
Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
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.
Asynchronously creates a directory.
The callback is given a possible exception and, if recursive is true, the first directory path created, (err[, path]).path can still be undefined when recursive is true, if no directory was created (for instance, if it was previously created).
The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false. If recursive is false and the directory exists, an EEXIST error occurs.
import { mkdir } from 'node:fs';
// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
On Windows, using fs.mkdir() on the root directory even with recursion will result in an error:
import { mkdir } from 'node:fs';
mkdir('/', { recursive: true }, (err) => {
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
See the POSIX mkdir(2) documentation for more details.
Asynchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.
Asynchronous mkdir(2) - create a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.
Asynchronous mkdir(2) - create a directory with a mode of 0o777.
A path to a file. If a URL is provided, it must use the file: protocol.
Creates a unique temporary directory.
Generates six random characters to be appended behind a required prefix to create a unique temporary directory. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.
The created directory path is passed as a string to the callback's second parameter.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
The fs.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within/tmp, the prefixmust end with a trailing platform-specific path separator (import { sep } from 'node:path').
import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';
// The parent directory for the new temporary directory
const tmpDir = tmpdir();
// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmpabc123`.
// A new temporary directory is created at the file system root
// rather than *within* the /tmp directory.
});
// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmp/abc123`.
// A new temporary directory is created within
// the /tmp directory.
});
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
Asynchronous file open. See the POSIX open(2) documentation for more details.
mode sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see chmod.
The callback gets two arguments (err, fd).
Some characters ( : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.
Functions based on fs.open() exhibit this behavior as well:fs.writeFile(), fs.readFile(), etc.
See support of file system flags``.
Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.
A path to a file. If a URL is provided, it must use the file: protocol.
See support of file system flags``.
Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.
A path to a file. If a URL is provided, it must use the file: protocol.
Asynchronously open a directory. See the POSIX opendir(3) documentation for more details.
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
Asynchronously open a directory. See the POSIX opendir(3) documentation for more details.
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
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 an Object with bytesRead and buffer properties.
The buffer that the data will be written to.
The position in buffer to write the data to.
The number of bytes to read.
Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.
Similar to the above fs.read function, this version takes an optional options object. If not otherwise specified in an options object, buffer defaults to Buffer.alloc(16384), offset defaults to 0, length defaults to buffer.byteLength, - offset as of Node 17.6.0 position defaults to null
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 an Object with bytesRead and buffer properties.
The buffer that the data will be written to.
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 an Object with bytesRead and buffer properties.
The buffer that the data will be written to.
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 an Object with bytesRead and buffer properties.
Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames passed to the callback. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the files array will contain fs.Dirent objects.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
If called with withFileTypes: true the result data will be an array of Dirent.
Asynchronous readdir(3) - read a directory.
A path to a file. If a URL is provided, it must use the file: protocol.
Must include withFileTypes: true and encoding: 'buffer'.
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), where data is the contents of the file.
If no encoding is specified, then the raw buffer is returned.
If options is a string, then it specifies the encoding:
import { readFile } from 'node:fs';
readFile('/etc/passwd', 'utf8', callback);
When the path is a directory, the behavior of fs.readFile() and readFileSync is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.
import { readFile } from 'node:fs';
// macOS, Linux, and Windows
readFile('', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read ]
});
// FreeBSD
readFile('', (err, data) => {
// => null,
});
It is possible to abort an ongoing request using an AbortSignal. If a request is aborted the callback is called with an AbortError:
import { readFile } from 'node:fs';
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
// ...
});
// When you want to abort the request
controller.abort();
The fs.readFile() function buffers the entire file. To minimize memory costs, when possible prefer streaming via fs.createReadStream().
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.
filename or file descriptor
Asynchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
Asynchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
Asynchronously reads the entire contents of a file.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
Reads the contents of the symbolic link referred to by path. The callback gets two arguments (err, linkString).
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path passed to the callback. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.
Asynchronous readlink(2) - read value of a symbolic link.
A path to a file. If a URL is provided, it must use the file: protocol.
Read from a file specified by fd and write to an array of ArrayBufferViews using readv().
position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.
The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffers properties.
Read from a file specified by fd and write to an array of ArrayBufferViews using readv().
position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.
The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffers properties.
Asynchronously rename file at oldPath to the pathname provided as newPath. In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.
See also: rename(2).
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.
Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.
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 an ENOENT error on Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use rm with options { recursive: true, force: true }.
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir -- file.txt - app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
A path to an existing file or directory on the file system to be queried.
Creates the link called path pointing to target. No arguments other than a possible exception are given to the completion callback.
See the POSIX symlink(2) documentation for more details.
The type argument is only available on Windows and ignored on other platforms. It can be set to 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', thetarget argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.
Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs';
symlink('./mew', './mewtwo', callback);
The above example creates a symbolic link mewtwo which points to mew in the same directory:
tree .
. ├── mew └── mewtwo -> ./mew
Asynchronous symlink(2) - Create a new symbolic link to an existing file.
A path to an existing file. If a URL is provided, it must use the file: protocol.
A path to the new symlink. If a URL is provided, it must use the file: protocol.
Asynchronous truncate(2) - Truncate a file to a specified length.
A path to a file. If a URL is provided, it must use the file: protocol.
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.
Change the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
Values can be either numbers representing Unix epoch time 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, an Error will be thrown.Write buffer to the file specified by fd.
offset determines the part of the buffer to be written, and length is an integer specifying the number of bytes to write.
position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position. See pwrite(2).
The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesWritten and buffer properties.
It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
The part of the buffer to be written. If not supplied, defaults to 0.
The number of bytes to write. If not supplied, defaults to buffer.length - offset.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
The part of the buffer to be written. If not supplied, defaults to 0.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
Asynchronously writes buffer to the file referenced by the supplied file descriptor.
A file descriptor.
An object with the following properties:
offset The part of the buffer to be written. If not supplied, defaults to 0.length The number of bytes to write. If not supplied, defaults to buffer.length - offset.position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.Asynchronously writes string to the file referenced by the supplied file descriptor.
A file descriptor.
A string to write.
The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
The expected string encoding.
Asynchronously writes string to the file referenced by the supplied file descriptor.
A file descriptor.
A string to write.
The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
Asynchronously writes string to the file referenced by the supplied file descriptor.
A file descriptor.
A string to write.
When file is a filename, asynchronously writes data to the file, replacing the file if it already exists. data can be a string or a buffer.
When file is a file descriptor, the behavior is similar to calling fs.write() directly (which is recommended). See the notes below on using a file descriptor.
The encoding option is ignored if data is a buffer.
The mode option only affects the newly created file. See open for more details.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
If options is a string, then it specifies the encoding:
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.
Similarly to fs.readFile - fs.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.
It is possible to use an AbortSignal to cancel an fs.writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
// When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs.
filename or file descriptor
Asynchronously writes data to a file, replacing the file if it already exists.
A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
Write an array of ArrayBufferViews to the file specified by fd using writev().
position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.
The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
Write an array of ArrayBufferViews to the file specified by fd using writev().
position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.
The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
Current working directory.
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return true to exclude the item, false to include it. 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.
true if the glob should return paths as Dirents, false otherwise.
Available blocks for unprivileged users
Free blocks in file system.
Total data blocks in file system.
Optimal transfer block size.
Free file nodes in file system.
Total file nodes in file system.
Type of file system.
Dereference symlinks
When force is false, and the destination exists, throw an error.
Function to filter copied files/directories. Return true to copy the item, false to ignore it.
Overwrite existing file or directory. _The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior.
Modifiers for copy operation. See mode flag of ()
When true timestamps from src will be preserved.
Copy directories recursively.
When true, path resolution for symlinks will be skipped
Dereference symlinks
When force is false, and the destination exists, throw an error.
Overwrite existing file or directory. _The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior.
Modifiers for copy operation. See mode flag of ()
When true timestamps from src will be preserved.
Copy directories recursively.
When true, path resolution for symlinks will be skipped
Dereference symlinks
When force is false, and the destination exists, throw an error.
Function to filter copied files/directories. Return true to copy the item, false to ignore it.
Overwrite existing file or directory. _The copy operation will ignore errors if you set this to false and the destination exists. Use the errorOnExist option to change this behavior.
Modifiers for copy operation. See mode flag of ()
When true timestamps from src will be preserved.
Copy directories recursively.
When true, path resolution for symlinks will be skipped
The path of the created directory.
The same as remove.
A function which removes the created directory.
This is the interface from which event-emitting Node.js APIs inherit in the types package. It is not intended for consumer use.
It provides event-mapped definitions similar to EventEmitter, except that its signatures are deliberately permissive: they provide type hinting, but not rigid type-checking, for compatibility reasons.
Classes that inherit directly from EventEmitter in JavaScript can inherit directly from this interface in the type definitions. Classes that are more than one inheritance level away from EventEmitter (eg. net.Socket > stream.Duplex > EventEmitter) must instead copy these method definitions into the derived class. Search "#region InternalEventEmitter" for examples.
The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
[captureRejectionSymbol](err, event, ...args) {
console.log('rejection happened for', event, 'with', err, ...args);
this.destroy(err);
}
destroy(err) {
// Tear the resource down here.
}
}
Alias for emitter.on(eventName, listener).
Alias for emitter.on(eventName, listener).
Stop watching for changes on the given fs.FSWatcher. Once stopped, the fs.FSWatcher object is no longer usable.
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Returns an array listing the events for which the emitter has registered listeners.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler function
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler 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] ]
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] ]
Alias for emitter.removeListener().
Alias for emitter.removeListener().
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback 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');
Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active. Calling watcher.ref() multiple times will have no effect.
By default, all fs.FSWatcher objects are "ref'ed", making it normally unnecessary to call watcher.ref() unless watcher.unref() had been called previously.
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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.
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked. Calling watcher.unref() multiple times will have no effect.
Current working directory.
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return true to exclude the item, false to include it. 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.
true if the glob should return paths as Dirents, false otherwise.
Current working directory.
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return true to exclude the item, false to include it. 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.
true if the glob should return paths as Dirents, false otherwise.
Current working directory.
Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return true to exclude the item, false to include it. 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.
true if the glob should return paths as Dirents, false otherwise.
A file mode. If a string is passed, it is parsed as an octal integer. If not specified
Indicates whether parent folders should be created. If a folder was created, the path to the first created folder will be returned.
An optional mime type for the blob.
Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage.
When true, exceptions will be ignored if path does not exist.
If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js will retry the operation with a linear backoff wait of retryDelay ms longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true.
If true, perform a recursive directory removal. In recursive mode, operations are retried on failure.
The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true.
Available blocks for unprivileged users
Free blocks in file system.
Total data blocks in file system.
Optimal transfer block size.
Free file nodes in file system.
Total file nodes in file system.
Type of file system.
Class: fs.StatWatcher
The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
[captureRejectionSymbol](err, event, ...args) {
console.log('rejection happened for', event, 'with', err, ...args);
this.destroy(err);
}
destroy(err) {
// Tear the resource down here.
}
}
Alias for emitter.on(eventName, listener).
Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Returns an array listing the events for which the emitter has registered listeners.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.
Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.
The name of the event being listened for
The event handler 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] ]
Alias for emitter.removeListener().
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
The callback function
Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
When called, requests that the Node.js event loop not exit so long as the fs.StatWatcher is active. Calling watcher.ref() multiple times will have no effect.
By default, all fs.StatWatcher objects are "ref'ed", making it normally unnecessary to call watcher.ref() unless watcher.unref() had been called previously.
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes the specified listener from the listener array for the event named eventName.
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 specified eventName, then removeListener() 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() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indexes 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 the once('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.
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
When called, the active fs.StatWatcher object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the fs.StatWatcher object's callback is invoked. Calling watcher.unref() multiple times will have no effect.
Appends writes to dest file instead of truncating it.
Which type of data you can send to the write function, supported values are 'utf8' or 'buffer'.
A path to a file to be written to (mode controlled by the append option).
A file descriptor, something that is returned by fs.open() or fs.openSync().
An object that has the same API as the fs module, useful for mocking, testing, or customizing the behavior of the stream.
Perform a fs.fsyncSync() every time a write is completed.
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
The maximum number of bytes that can be written;
The minimum length of the internal buffer that is required to be full before flushing.
Ensure directory for dest file exists when true.
Specify the creating file mode (see fs.open()).
Calls flush every periodicFlush milliseconds.
A function that will be called when write(), writeSync(), or flushSync() encounters an EAGAIN or EBUSY error. If the return value is true the operation will be retried, otherwise it will bubble the error. The err is the error that caused this function to be called, writeBufferLen is the length of the buffer that was written, and remainingBufferLen is the length of the remaining buffer that the stream did not try to write.
Perform writes synchronously.
Watch for changes on filename. The callback listener will be called each time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).
This happens when:
the file is deleted, followed by a restorethe file is renamed and then renamed a second time back to its original nameValid types for path values in "fs".
Resources
ReferenceDocsGuidesDiscordMerch StoreGitHubBlogToolkit
RuntimePackage managerTest runnerBundlerPackage runnerProject
Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicenseBaked with ❤️ in San Francisco
We're hiring →Node.js fs module | API Reference | Bun,AI智能索引,全网链接索引,智能导航,网页索引
- The