Abstract
Static
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAdd a cursor flag to the cursor
+The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
+The flag boolean value.
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Set the batch size for the cursor.
+The number of documents to return per batch. See command documentation.
+Abstract
cloneReturns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
+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
+
+
+Rest
...args: Parameters<CursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Set the ReadPreference for the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]The Admin class is an internal class that allows convenient access to +the admin functionality and commands for MongoDB.
+ADMIN Cannot directly be instantiated
+Retrieve the server build information
+Optional
options: CommandOperationOptionsOptional settings for the command
+Execute a command
+The driver will ensure the following fields are attached to the command sent to the server:
+lsid
- sourced from an implicit session or options.session$readPreference
- defaults to primary or can be configured by options.readPreference$db
- sourced from the name of this databaseIf the client has a serverApi setting:
+apiVersion
apiStrict
apiDeprecationErrors
When in a transaction:
+readConcern
- sourced from readConcern set on the TransactionOptionswriteConcern
- sourced from writeConcern set on the TransactionOptionsAttaching any of the above fields to the command will have no effect as the driver will overwrite the value.
+The command to execute
+Optional
options: RunCommandOptionsOptional settings for the command
+List the available databases
+Optional
options: ListDatabasesOptionsOptional settings for the command
+Ping the MongoDB server and retrieve results
+Optional
options: CommandOperationOptionsOptional settings for the command
+Remove a user from a database
+The username to remove
+Optional
options: CommandOperationOptionsOptional settings for the command
+Get ReplicaSet status
+Optional
options: CommandOperationOptionsOptional settings for the command
+Retrieve the server build information
+Optional
options: CommandOperationOptionsOptional settings for the command
+Retrieve this db's server status.
+Optional
options: CommandOperationOptionsOptional settings for the command
+Validate an existing collection
+The name of the collection to validate.
+Optional settings for the command
+The AggregationCursor class is an internal class that embodies an aggregation cursor on MongoDB +allowing for iteration over the results returned from the underlying query. It supports +one by one document iteration, conversion to an array or can be iterated as a Node 4.X +or higher stream
+An alias for AbstractCursor.close|AbstractCursor.close().
+Readonly
pipelineStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAdd a cursor flag to the cursor
+The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
+The flag boolean value.
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Add a stage to the aggregation pipeline
+Set the batch size for the cursor.
+The number of documents to return per batch. See command documentation.
+Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
+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
+
+
+Rest
...args: Parameters<AbstractCursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Execute the explain for the cursor
+Optional
verbosity: ExplainVerbosityLikeAdd a geoNear stage to the aggregation pipeline
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.
Add a group stage to the aggregation pipeline
+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.
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] ]
+
+
+Add a lookup stage to the aggregation pipeline
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Add a match stage to the aggregation pipeline
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Add a project stage to the aggregation pipeline
+In order to strictly type this function you must provide an interface +that represents the effect of your projection on the result documents.
+By default chaining a projection to your cursor changes the returned type to the generic Document type. +You should specify a parameterized type to have assertions on your final results.
+// Best way
const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
// Flexible way
const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
+
+
+const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
// or always use chaining and save the final cursor
const cursor = coll.aggregate().project<{ a: string }>({
_id: 0,
a: { $convert: { input: '$a', to: 'string' }
}});
+
+
+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');
+
+
+Add a redact stage to the aggregation pipeline
+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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Add a sort stage to the aggregation pipeline
+Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Add a unwind stage to the aggregation pipeline
+Set the ReadPreference for the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Optional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureStatic
isBSONErrorAll errors thrown from the BSON library inherit from BSONError
.
+This method can assist with determining if an error originates from the BSON library
+even if it does not pass an instanceof
check against this class' constructor.
any javascript value that needs type checking
+Experimental
Experimental
Optional
options: { Optional
cause?: unknownOptional
Experimental
causeExperimental
messageExperimental
offsetOptional
Experimental
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
Experimental
stackStatic
captureStatic
isBSONErrorAll errors thrown from the BSON library inherit from BSONError
.
+This method can assist with determining if an error originates from the BSON library
+even if it does not pass an instanceof
check against this class' constructor.
any javascript value that needs type checking
+A class representation of the BSON RegExp type.
+The regular expression pattern to match
+Optional
options: stringThe regular expression options
+Optional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureStatic
isBSONErrorAll errors thrown from the BSON library inherit from BSONError
.
+This method can assist with determining if an error originates from the BSON library
+even if it does not pass an instanceof
check against this class' constructor.
any javascript value that needs type checking
+A class representation of the BSON Symbol type.
+the string representing the symbol.
+Optional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureStatic
isBSONErrorAll errors thrown from the BSON library inherit from BSONError
.
+This method can assist with determining if an error originates from the BSON library
+even if it does not pass an instanceof
check against this class' constructor.
any javascript value that needs type checking
+A class representation of the BSON Binary type.
+Create a new Binary instance.
+Optional
buffer: BinarySequencea buffer object containing the binary data.
+Optional
subType: numberthe option binary type.
+Static
Readonly
BUFFER_Initial buffer default size
+Static
Readonly
SUBTYPE_Byte Array BSON type
+Static
Readonly
SUBTYPE_Column BSON type
+Static
Readonly
SUBTYPE_Default BSON type
+Static
Readonly
SUBTYPE_Encrypted BSON type
+Static
Readonly
SUBTYPE_Function BSON type
+Static
Readonly
SUBTYPE_MD5 BSON type
+Static
Readonly
SUBTYPE_Sensitive BSON type
+Static
Readonly
SUBTYPE_User BSON type
+Static
Readonly
SUBTYPE_UUID BSON type
+Static
Readonly
SUBTYPE_Deprecated UUID BSON type
+Reads length bytes starting at position.
+read from the given position in the Binary.
+the number of bytes to read.
+Writes a buffer to the binary.
+a string or buffer to be written to the Binary BSON object.
+specify the binary of where to write the content.
+Static
createStatic
createA class representation of the BSON Decimal128 type.
+a buffer containing the raw Decimal128 bytes in little endian order, +or a string representation as returned by .toString()
+Static
fromCreate a Decimal128 instance from a string representation
+a numeric string representation.
+Static
fromCreate a Decimal128 instance from a string representation, allowing for rounding to 34 +significant digits
+a numeric string representation.
+> let d = Decimal128.fromString('37.499999999999999196428571428571375')
Uncaught:
BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding
at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11)
at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25)
at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27)
> d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375')
new Decimal128("37.49999999999999919642857142857138")
+
+
+A class representation of the BSON Double type.
+Static
fromAttempt to create an double type from string.
+This method will throw a BSONError on any string input that is not representable as a IEEE-754 64-bit double. +Notably, this method will also throw on the following string formats:
+Strings with leading zeros, however, are also allowed
+the string we want to represent as a double.
+A class representation of a BSON Int32 type.
+Static
fromAttempt to create an Int32 type from string.
+This method will throw a BSONError on any string input that is not representable as an Int32. +Notably, this method will also throw on the following string formats:
+Strings with leading zeros, however, are allowed.
+the string we want to represent as an int32.
+A class representing a 64-bit integer
+The internal representation of a long is the two given signed, 32-bit values. +We use 32-bit pieces because these are the size of integers on which +Javascript performs bit-operations. For operations like addition and +multiplication, we split each number into 16 bit pieces, which can easily be +multiplied within Javascript's floating-point representation without overflow +or change in sign. +In the algorithms below, we frequently reduce the negative case to the +positive case by negating the input(s) and then post-processing the result. +Note that we must ALWAYS check specially whether those values are MIN_VALUE +(-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as +a positive number, it overflows back into a negative). Not handling this +case would often result in infinite recursion. +Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
+Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers.
+The low (signed) 32 bits of the long
+Optional
high: numberThe high (signed) 32 bits of the long
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+Constructs a 64 bit two's-complement integer, given a bigint representation.
+BigInt representation of the long value
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+Constructs a 64 bit two's-complement integer, given a string representation.
+String representation of the long value
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+The high 32 bits as a signed value.
+The low 32 bits as a signed value.
+Whether unsigned or not.
+Static
MAX_Maximum unsigned value.
+Static
MAX_Maximum signed value.
+Static
MIN_Minimum signed value.
+Static
NEG_Signed negative one.
+Static
ONESigned one.
+Static
TWO_Static
UONEUnsigned one.
+Static
UZEROUnsigned zero.
+Static
ZEROSigned zero
+An indicator used to reliably determine if an object is a Long or not.
+This is an alias of Long.compare
+This is an alias of Long.divide
+This is an alias of Long.equals
+This is an alias of Long.isZero
+This is an alias of Long.greaterThanOrEqual
+This is an alias of Long.greaterThan
+This is an alias of Long.greaterThanOrEqual
+This is an alias of Long.lessThanOrEqual
+This is an alias of Long#lessThan.
+This is an alias of Long.lessThanOrEqual
+This is an alias of Long.modulo
+This is an alias of Long.multiply
+This is an alias of Long.notEquals
+This is an alias of Long.negate
+This is an alias of Long.notEquals
+This is an alias of Long.modulo
+This is an alias of Long.shiftLeft
+This is an alias of Long.shiftRight
+This is an alias of Long.shiftRightUnsigned
+This is an alias of Long.shiftRightUnsigned
+This is an alias of Long.subtract
+Optional
options: EJSONOptionsStatic
fromReturns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
+The number in question
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+The corresponding Long value
+Static
fromReturns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. +Each is assumed to use 32 bits.
+The low 32 bits
+The high 32 bits
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+The corresponding Long value
+Static
fromCreates a Long from its byte representation.
+Byte representation
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+Optional
le: booleanWhether little or big endian, defaults to big endian
+The corresponding Long value
+Static
fromStatic
fromStatic
fromOptional
options: EJSONOptionsStatic
fromStatic
fromReturns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
+The number in question
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+The corresponding Long value
+Static
fromReturns a signed Long representation of the given string, written using radix 10.
+If the input string is empty, this function will throw a BSONError.
+If input string does not have valid signed 64-bit Long representation, this method will return a coerced value:
+The textual representation of the Long
+The corresponding Long value
+Returns a signed Long representation of the given string, written using the provided radix.
+If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
+If input parameters do not have valid signed 64-bit Long representation, this method will return a coerced value:
+The textual representation of the Long
+Optional
radix: numberThe radix in which the text is written (2-36), defaults to 10
+The corresponding Long value
+Returns a Long representation of the given string, written using radix 10.
+If the input string is empty, this function will throw a BSONError.
+If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
+The textual representation of the Long
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+The corresponding Long value
+Returns a Long representation of the given string, written using the specified radix.
+If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
+If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
+The textual representation of the Long
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+Optional
radix: numberThe radix in which the text is written (2-36), defaults to 10
+The corresponding Long value
+Static
fromReturns a signed Long representation of the given string, written using radix 10. +Will throw an error if the given text is not exactly representable as a Long. +Throws an error if any of the following conditions are true:
+The textual representation of the Long
+The corresponding Long value
+Returns a Long representation of the given string, written using the radix 10. +Will throw an error if the given parameters are not exactly representable as a Long. +Throws an error if any of the following conditions are true:
+The textual representation of the Long
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+The corresponding Long value
+Returns a signed Long representation of the given string, written using the specified radix. +Will throw an error if the given parameters are not exactly representable as a Long. +Throws an error if any of the following conditions are true:
+The textual representation of the Long
+Optional
radix: booleanThe radix in which the text is written (2-36), defaults to 10
+The corresponding Long value
+Returns a Long representation of the given string, written using the specified radix. +Will throw an error if the given parameters are not exactly representable as a Long. +Throws an error if any of the following conditions are true:
+The textual representation of the Long
+Optional
unsigned: booleanWhether unsigned or not, defaults to signed
+Optional
radix: numberThe radix in which the text is written (2-36), defaults to 10
+The corresponding Long value
+Static
fromStatic
isA class representation of the BSON ObjectId type.
+Create ObjectId from a number.
+A number.
+Create ObjectId from a 24 character hex string.
+A 24 character hex string.
+Create ObjectId from the BSON ObjectId type.
+The BSON ObjectId type.
+Create ObjectId from the object type that has the toHexString method.
+The ObjectIdLike type.
+Create ObjectId from a 12 byte binary Buffer.
+A 12 byte binary Buffer.
+To generate a new ObjectId, use ObjectId() with no argument.
+Implementation overload.
+Optional
inputId: All input types that are used in the constructor implementation.
+The ObjectId bytes
+Compares the equality of this ObjectId with otherID
.
ObjectId instance to compare against.
+Static
createStatic
createStatic
createStatic
generateStatic
isChecks if a value can be used to create a valid bson ObjectId
+any JS value
+A 64-bit bigint representing the Timestamp.
+A 64-bit Long representing the Timestamp.
+A pair of two values indicating timestamp and increment.
+This is an alias of Long.compare
+This is an alias of Long.divide
+This is an alias of Long.equals
+This is an alias of Long.isZero
+This is an alias of Long.greaterThanOrEqual
+Gets the high 32 bits as a signed integer.
+Gets the high 32 bits as an unsigned integer.
+Gets the low 32 bits as a signed integer.
+Gets the low 32 bits as an unsigned integer.
+Gets the number of bits needed to represent the absolute value of this Long.
+This is an alias of Long.greaterThan
+This is an alias of Long.greaterThanOrEqual
+Tests if this Long's value is even.
+Tests if this Long's value is negative.
+Tests if this Long's value is odd.
+Tests if this Long's value is positive.
+Tests if this Long's value equals zero.
+This is an alias of Long.lessThanOrEqual
+This is an alias of Long#lessThan.
+This is an alias of Long.lessThanOrEqual
+This is an alias of Long.modulo
+This is an alias of Long.multiply
+This is an alias of Long.notEquals
+This is an alias of Long.negate
+This is an alias of Long.notEquals
+This is an alias of Long.modulo
+This is an alias of Long.shiftLeft
+This is an alias of Long.shiftRight
+This is an alias of Long.shiftRightUnsigned
+This is an alias of Long.shiftRightUnsigned
+This is an alias of Long.subtract
+Converts the Long to a BigInt (arbitrary precision).
+Converts this Long to its byte representation.
+Optional
le: booleanWhether little or big endian, defaults to big endian
+Byte representation
+Converts this Long to its big endian byte representation.
+Big endian byte representation
+Converts this Long to its little endian byte representation.
+Little endian byte representation
+Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
+Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
+Static
Readonly
MAX_A class representation of the BSON UUID type.
+Static
Readonly
BUFFER_Initial buffer default size
+Static
Readonly
SUBTYPE_Byte Array BSON type
+Static
Readonly
SUBTYPE_Column BSON type
+Static
Readonly
SUBTYPE_Default BSON type
+Static
Readonly
SUBTYPE_Encrypted BSON type
+Static
Readonly
SUBTYPE_Function BSON type
+Static
Readonly
SUBTYPE_MD5 BSON type
+Static
Readonly
SUBTYPE_Sensitive BSON type
+Static
Readonly
SUBTYPE_User BSON type
+Static
Readonly
SUBTYPE_UUID BSON type
+Static
Readonly
SUBTYPE_Deprecated UUID BSON type
+The UUID bytes
+Compares the equality of this UUID with otherID
.
UUID instance to compare against.
+Reads length bytes starting at position.
+read from the given position in the Binary.
+the number of bytes to read.
+Writes a buffer to the binary.
+a string or buffer to be written to the Binary BSON object.
+specify the binary of where to write the content.
+Static
createStatic
createStatic
generateStatic
isKeeps the state of a unordered batch so we can rewrite the results +correctly after command execution
+Abstract
Abstract
addBuilds a find operation for an update/updateOne/delete/deleteOne/replaceOne. +Returns a builder object used to complete the definition of the operation.
+const bulkOp = collection.initializeOrderedBulkOp();
// Add an updateOne to the bulkOp
bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
// Add an updateMany to the bulkOp
bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
// Add an upsert
bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
// Add a deletion
bulkOp.find({ g: 7 }).deleteOne();
// Add a multi deletion
bulkOp.find({ h: 8 }).delete();
// Add a replaceOne
bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
// Update using a pipeline (requires Mongodb 4.2 or higher)
bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
{ $set: { total: { $sum: [ '$y', '$z' ] } } }
]);
// All of the ops will now be executed
await bulkOp.execute();
+
+
+Add a single insert document to the bulk operation
+The result of a bulk write.
+Readonly
deletedNumber of documents deleted.
+Readonly
insertedNumber of documents inserted.
+Readonly
insertedInserted document generated Id's, hash key is the index of the originating operation
+Readonly
matchedNumber of documents matched for update.
+Readonly
modifiedNumber of documents modified.
+Readonly
upsertedNumber of documents upserted.
+Readonly
upsertedUpserted document generated Id's, hash key is the index of the originating operation
+Evaluates to true if the bulk operation correctly executes
+Retrieve the write concern error if one exists
+Returns a specific write error object
+Retrieve all write errors
+Optional
options: EventEmitterOptionsStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
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. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
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()
.
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
+
+
+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 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 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
+
+
+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 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 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.
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 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 callback function
+Adds a one-timelistener
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.
Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Creates a new Change Stream instance. Normally created using Collection.watch().
+An alias for ChangeStream.close|ChangeStream.close().
+Optional
streamStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CHANGEFired for each new matching change in the specified namespace. Attaching a change
+event listener to a Change Stream will switch the stream into flowing mode. Data will
+then be passed as soon as it is available.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
ENDStatic
Readonly
ERRORStatic
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Static
Readonly
INITStatic
Readonly
MOREStatic
Readonly
RESPONSEStatic
Readonly
RESUME_Emitted each time the change stream stores a new resume token.
+Is the cursor closed
+The cached resume token that is used to resume after the most recently returned change.
+Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
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
+
+
+Rest
...args: Parameters<ChangeStreamEvents<TSchema, TChange>[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
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()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Return a modified Readable stream including a possible transform method.
+NOTE: When using a Stream to process change stream events, the stream will +NOT automatically resume in the case a resumable error is encountered.
+Optional
options: CursorStreamOptionsStatic
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]The public interface for explicit in-use encryption
+Create a new encryption instance
+new ClientEncryption(mongoClient, {
keyVaultNamespace: 'client.encryption',
kmsProviders: {
local: {
key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
}
}
});
+
+
+new ClientEncryption(mongoClient, {
keyVaultNamespace: 'client.encryption',
kmsProviders: {
aws: {
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_KEY
}
}
});
+
+
+Adds a keyAltName to a key identified by the provided _id.
+This method resolves to/returns the old key value (prior to adding the new altKeyName).
+The id of the document to update.
+a keyAltName to search for a key
+Returns a promise that either resolves to a DataKey if a document matches the key or null if no documents +match the id. The promise rejects with an error if an error is thrown.
+// adding an keyAltName to a data key
const id = new Binary(); // id is a bson binary subtype 4 object
const keyAltName = 'keyAltName';
const oldKey = await clientEncryption.addKeyAltName(id, keyAltName);
if (!oldKey) {
// null is returned if there is no matching document with an id matching the supplied id
}
+
+
+Creates a data key used for explicit encryption and inserts it into the key vault namespace
+// Using async/await to create a local key
const dataKeyId = await clientEncryption.createDataKey('local');
+
+
+// Using async/await to create an aws key
const dataKeyId = await clientEncryption.createDataKey('aws', {
masterKey: {
region: 'us-east-1',
key: 'xxxxxxxxxxxxxx' // CMK ARN here
}
});
+
+
+// Using async/await to create an aws key with a keyAltName
const dataKeyId = await clientEncryption.createDataKey('aws', {
masterKey: {
region: 'us-east-1',
key: 'xxxxxxxxxxxxxx' // CMK ARN here
},
keyAltNames: [ 'mySpecialKey' ]
});
+
+
+A convenience method for creating an encrypted collection.
+This method will create data keys for any encryptedFields that do not have a keyId
defined
+and then create a new collection with the full set of encryptedFields.
A Node.js driver Db object with which to create the collection
+The name of the collection to be created
+Options for createDataKey and for createCollection
+Optional
mastercreated collection and generated encryptedFields
+MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial encryptedFields
that were created.
MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire encryptedFields
that were created.
Deletes the key with the provided id from the keyvault, if it exists.
+Explicitly encrypt a provided value. Note that either options.keyId
or options.keyAltName
must
+be specified. Specifying both options.keyId
and options.keyAltName
is considered an error.
The value that you wish to serialize. Must be of a type that can be serialized into BSON
+a Promise that either resolves with the encrypted value, or rejects with an error.
+// Encryption with async/await api
async function encryptMyData(value) {
const keyId = await clientEncryption.createDataKey('local');
return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
}
+
+
+// Encryption using a keyAltName
async function encryptMyData(value) {
await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
}
+
+
+Encrypts a Match Expression or Aggregate Expression to query a range index.
+Only supported when queryType is "range" and algorithm is "Range".
+a BSON document of one of the following forms:
+{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}
{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}
$gt
may also be $gte
. $lt
may also be $lte
.
Returns a Promise that either resolves with the encrypted value or rejects with an error.
+Finds a key in the keyvault with the specified _id.
+Returns a promise that either resolves to a DataKey if a document matches the key or null if no documents +match the id. The promise rejects with an error if an error is thrown.
+Finds a key in the keyvault which has the specified keyAltName.
+a keyAltName to search for a key
+Returns a promise that either resolves to a DataKey if a document matches the key or null if no documents +match the keyAltName. The promise rejects with an error if an error is thrown.
+Finds all the keys currently stored in the keyvault.
+This method will not throw.
+a FindCursor over all keys in the keyvault.
+Adds a keyAltName to a key identified by the provided _id.
+This method resolves to/returns the old key value (prior to removing the new altKeyName).
+If the removed keyAltName is the last keyAltName for that key, the altKeyNames
property is unset from the document.
The id of the document to update.
+a keyAltName to search for a key
+Returns a promise that either resolves to a DataKey if a document matches the key or null if no documents +match the id. The promise rejects with an error if an error is thrown.
+// removing a key alt name from a data key
const id = new Binary(); // id is a bson binary subtype 4 object
const keyAltName = 'keyAltName';
const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName);
if (!oldKey) {
// null is returned if there is no matching document with an id matching the supplied id
}
+
+
+Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options.
+If no matches are found, then no bulk write is performed.
+// rewrapping all data data keys (using a filter that matches all documents)
const filter = {};
const result = await clientEncryption.rewrapManyDataKey(filter);
if (result.bulkWriteResult != null) {
// keys were re-wrapped, results will be available in the bulkWrite object.
}
+
+
+// attempting to rewrap all data keys with no matches
const filter = { _id: new Binary() } // assume _id matches no documents in the database
const result = await clientEncryption.rewrapManyDataKey(filter);
if (result.bulkWriteResult == null) {
// no keys matched, `bulkWriteResult` does not exist on the result object
}
+
+
+A class representing a client session on the server
+NOTE: not meant to be instantiated directly.
+An alias for ClientSession.endSession().
+Optional
clientOptional
clusterOptional
operationStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The server id associated with this session
+Whether or not this session is configured for snapshot reads
+Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
+the $clusterTime returned by the server from another session in the form of a document containing the BSON.Timestamp
clusterTime and signature
Advances the operationTime for a ClientSession.
+the BSON.Timestamp
of the operation type it is desired to advance to
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
+
+
+Rest
...args: Parameters<ClientSessionEvents[EventKey]>Frees any client-side resources held by the current session. If a session is in a transaction, +the transaction is aborted.
+Does not end the session on the server.
+Optional
options: EndSessionOptionsOptional settings. Currently reserved for future use
+Used to determine if this session equals another
+The session to compare to
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
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()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Starts a new transaction with the given options.
+Optional
options: TransactionOptionsOptions for the transaction
+Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed.
+IMPORTANT: This method requires the function passed in to return a Promise. That promise must be made by await
-ing all operations in such a way that rejections are propagated to the returned promise.
IMPORTANT: Running operations in parallel is not supported during a transaction. The use of Promise.all
,
+Promise.allSettled
, Promise.race
, etc to parallelize operations inside a transaction is
+undefined behaviour.
callback to run within a transaction
+Optional
options: TransactionOptionsoptional settings for the transaction
+A raw command response or undefined
+commitTransaction
operation is successful, then the provided function will return the result of the provided function.Checkout a descriptive example here:
+https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
+If a command inside withTransaction fails:
+To avoid this situation, the application must not silently handle errors within the provided function. +If the application needs to handle errors within, it must await all operations such that if an operation is rejected it becomes the rejection of the callback function passed into withTransaction.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]The Collection class is an internal class that embodies a MongoDB collection +allowing for insert/find/update/delete and other command operation on that MongoDB collection.
+COLLECTION Cannot directly be instantiated
+import { MongoClient } from 'mongodb';
interface Pet {
name: string;
kind: 'dog' | 'cat' | 'fish';
}
const client = new MongoClient('mongodb://localhost:27017');
const pets = client.db().collection<Pet>('pets');
const petCursor = pets.find();
for await (const pet of petCursor) {
console.log(`${pet.name} is a ${pet.kind}!`);
}
+
+
+The name of this collection
+The name of the database this collection belongs to
+The namespace of this collection, in the format ${this.dbName}.${this.collectionName}
The current readConcern of the collection. If not explicitly defined for +this collection, will be inherited from the parent DB
+The current readPreference of the collection. If not explicitly defined for +this collection, will be inherited from the parent DB
+The current writeConcern of the collection. If not explicitly defined for +this collection, will be inherited from the parent DB
+Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
+An array of aggregation pipelines to execute
+Optional
options: AggregateOptionsOptional settings for the command
+Perform a bulkWrite operation without a fluent API
+Legal operation types are
+insertOne
replaceOne
updateOne
updateMany
deleteOne
deleteMany
If documents passed in do not contain the _id field, +one will be added to each of the documents missing it by the driver, mutating the document. This behavior +can be overridden by setting the forceServerObjectId flag.
+Bulk operations to perform
+Optional
options: BulkWriteOptionsOptional settings for the command
+An estimated count of matching documents in the db to a filter.
+NOTE: This method has been deprecated, since it does not provide an accurate count of the documents +in a collection. To obtain an accurate count of documents in the collection, use Collection#countDocuments| countDocuments. +To obtain an estimated count of all documents in the collection, use Collection#estimatedDocumentCount| estimatedDocumentCount.
+The filter for the count.
+Optional settings for the command
+Gets the number of documents matching the filter. +For a fast count of the total documents in a collection see Collection#estimatedDocumentCount| estimatedDocumentCount. +Note: When migrating from Collection#count| count to Collection#countDocuments| countDocuments +the following query operators must be replaced:
+Operator | +Replacement | +
---|---|
$where |
+$expr |
+
$near |
+$geoWithin with $center |
+
$nearSphere |
+$geoWithin with $centerSphere |
+
The filter for the count
+Optional settings for the command
+Creates an index on the db and collection collection.
+The field name or index specification to create an index for
+Optional
options: CreateIndexesOptionsOptional settings for the command
+const collection = client.db('foo').collection('bar');
await collection.createIndex({ a: 1, b: -1 });
// Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
await collection.createIndex([ [c, 1], [d, -1] ]);
// Equivalent to { e: 1 }
await collection.createIndex('e');
// Equivalent to { f: 1, g: 1 }
await collection.createIndex(['f', 'g'])
// Equivalent to { h: 1, i: -1 }
await collection.createIndex([ { h: 1 }, { i: -1 } ]);
// Equivalent to { j: 1, k: -1, l: 2d }
await collection.createIndex(['j', ['k', -1], { l: '2d' }])
+
+
+Creates multiple indexes in the collection, this method is only supported for +MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported +error.
+Note: Unlike Collection#createIndex| createIndex, this function takes in raw index specifications. +Index specifications are defined here.
+An array of index specifications to be created
+Optional
options: CreateIndexesOptionsOptional settings for the command
+Creates a single search index for the collection.
+The index description for the new search index.
+A promise that resolves to the name of the new search index.
+Creates multiple search indexes for the current collection.
+An array of SearchIndexDescription
s for the new search indexes.
A promise that resolves to an array of the newly created search index names.
+Delete multiple documents from a collection
+The filter used to select the documents to remove
+Optional settings for the command
+Delete a document from a collection
+The filter used to select the document to remove
+Optional settings for the command
+The distinct command returns a list of distinct values for the given key across a collection.
+Field of the document to find distinct values for
+Drop the collection from the database, removing it permanently. New accesses will create a new collection.
+Optional
options: DropCollectionOptionsOptional settings for the command
+Drops an index from this collection.
+Name of the index to drop.
+Optional
options: CommandOperationOptionsOptional settings for the command
+Drops all indexes from this collection.
+Optional
options: CommandOperationOptionsOptional settings for the command
+Gets an estimate of the count of documents in a collection using collection metadata. +This will always run a count command on all server versions.
+due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, +which estimatedDocumentCount uses in its implementation, was not included in v1 of +the Stable API, and so users of the Stable API with estimatedDocumentCount are +recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid +encountering errors.
+Optional
options: EstimatedDocumentCountOptionsOptional settings for the command
+Creates a cursor for a filter that can be used to iterate over results from MongoDB
+Optional
options: FindOptions<Document>Optional
options: FindOptions<Document>Fetches the first document that matches the filter
+Optional
options: FindOptions<Document>Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
+The filter used to select the document to remove
+Optional settings for the command
+Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
+The filter used to select the document to replace
+The Document that replaces the matching document
+Optional settings for the command
+Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
+The filter used to select the document to update
+Update operations to be performed on the document
+Optional settings for the command
+Retrieve all the indexes on the collection.
+Optional settings for the command
+Optional
options: AbstractCursorOptionsChecks if one or more indexes exist on the collection, fails on first non-existing index
+One or more index names to check.
+Optional
options: AbstractCursorOptionsOptional settings for the command
+Retrieves this collections index info.
+Optional settings for the command
+Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.
+Optional
options: BulkWriteOptionsInitiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
+Optional
options: BulkWriteOptionsInserts an array of documents into MongoDB. If documents passed in do not contain the _id field, +one will be added to each of the documents missing it by the driver, mutating the document. This behavior +can be overridden by setting the forceServerObjectId flag.
+The documents to insert
+Optional
options: BulkWriteOptionsOptional settings for the command
+Inserts a single document into MongoDB. If documents passed in do not contain the _id field, +one will be added to each of the documents missing it by the driver, mutating the document. This behavior +can be overridden by setting the forceServerObjectId flag.
+The document to insert
+Optional
options: InsertOneOptionsOptional settings for the command
+Returns if the collection is a capped collection
+Optional
options: OperationOptionsOptional settings for the command
+Get the list of all indexes information for the collection.
+Optional
options: AbstractCursorOptionsOptional settings for the command
+Returns all search indexes for the current collection.
+Optional
options: ListSearchIndexesOptionsThe options for the list indexes operation.
+Returns all search indexes for the current collection.
+The name of the index to search for. Only indexes with matching index names will be returned.
+Optional
options: ListSearchIndexesOptionsThe options for the list indexes operation.
+Returns the options of the collection.
+Optional
options: OperationOptionsOptional settings for the command
+Rename the collection.
+New name of of the collection.
+Optional
options: RenameOptionsOptional settings for the command
+Replace a document in a collection with another document
+The filter used to select the document to replace
+The Document that replaces the matching document
+Optional
options: ReplaceOptionsOptional settings for the command
+Update multiple documents in a collection
+The value of update
can be either:
The filter used to select the document to update
+The modifications to apply
+Optional
options: UpdateOptionsOptional settings for the command
+Update a single document in a collection
+The value of update
can be either:
The filter used to select the document to update
+The modifications to apply
+Optional
options: UpdateOptionsOptional settings for the command
+Updates a search index by replacing the existing index definition with the provided definition.
+The name of the search index to update.
+The new search index definition.
+Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
+Type of the data being detected by the change stream
+Type of the whole change stream document emitted
+An array of pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
+Optional settings for the command
+watch() accepts two generic arguments for distinct use cases:
+By just providing the first argument I can type the change to be ChangeStreamDocument<{ _id: number }>
collection.watch<{ _id: number }>()
.on('change', change => console.log(change._id.toFixed(4)));
+
+
+Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. +Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. +No need start from scratch on the ChangeStreamInsertDocument type! +By using an intersection we can save time and ensure defaults remain the same type!
+collection
.watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([
{ $addFields: { comment: 'big changes' } },
{ $match: { operationType: 'insert' } }
])
.on('change', change => {
change.comment.startsWith('big');
change.operationType === 'insert';
// No need to narrow in code because the generics did that for us!
expectType<Schema>(change.fullDocument);
});
+
+
+An event indicating the failure of a given command
+Optional
connectionDriver generated connection id
+Server generated connection id +Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
+Optional
serviceAn event indicating the start of a given command
+Optional
commandOptional
connectionDriver generated connection id
+Server generated connection id +Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" +from the server on 4.2+.
+Optional
serviceAn event indicating the success of a given command
+Optional
connectionDriver generated connection id
+Server generated connection id +Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
+Optional
serviceAn event published when a request to check a connection out fails
+The address (host/port pair) of the pool
+The time it took to check out the connection.
+More specifically, the time elapsed between
+emitting a ConnectionCheckOutStartedEvent
+and emitting this event as part of the same check out.
The reason the attempt to check out failed
+A timestamp when the event was created
+An event published when a request to check a connection out begins
+An event published when a connection is checked into the connection pool
+An event published when a connection is checked out of the connection pool
+The address (host/port pair) of the pool
+The id of the connection
+The time it took to check out the connection.
+More specifically, the time elapsed between
+emitting a ConnectionCheckOutStartedEvent
+and emitting this event as part of the same checking out.
A timestamp when the event was created
+An event published when a connection is closed
+An event published when a connection pool creates a new connection
+An event published when a connection pool is cleared
+An event published when a connection pool is closed
+An event published when a connection pool is created
+The address (host/port pair) of the pool
+The options used to create this connection pool
+A timestamp when the event was created
+Abstract
The base export class for all monitoring events published from the connection pool
+An event published when a connection pool is ready
+An event published when a connection is ready for use
+The address (host/port pair) of the pool
+The id of the connection
+The time it took to establish the connection.
+In accordance with the definition of establishment of a connection
+specified by ConnectionPoolOptions.maxConnecting
,
+it is the time elapsed between emitting a ConnectionCreatedEvent
+and emitting this event as part of the same checking out.
Naturally, when establishing a connection is part of checking out,
+this duration is not greater than
+ConnectionCheckedOutEvent.duration
.
A timestamp when the event was created
+The Db class is a class that represents a MongoDB Database.
+import { MongoClient } from 'mongodb';
interface Pet {
name: string;
kind: 'dog' | 'cat' | 'fish';
}
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db();
// Create a collection that validates our union
await db.createCollection<Pet>('pets', {
validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }
})
+
+
+Creates a new Db instance.
+Db name cannot contain a dot, the server may apply more restrictions when an operation is run.
+The MongoClient for the database.
+The name of the database this instance represents.
+Optional
options: DbOptionsOptional settings for Db construction.
+Static
SYSTEM_Static
SYSTEM_Static
SYSTEM_Static
SYSTEM_Static
SYSTEM_Static
SYSTEM_The current readPreference of the Db. If not explicitly defined for +this Db, will be inherited from the parent MongoClient
+Check if a secondary can be used (because the read preference is not set to primary)
+Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6
+An array of aggregation stages to be executed
+Optional
options: AggregateOptionsOptional settings for the command
+Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
+Collection namespace validation is performed server-side.
+the collection name we wish to access.
+return the new Collection instance
+Fetch all collections for the current db.
+Optional
options: ListCollectionsOptionsOptional settings for the command
+Execute a command
+The command to run
+Optional
options: RunCommandOptionsOptional settings for the command
+This command does not inherit options from the MongoClient.
+The driver will ensure the following fields are attached to the command sent to the server:
+lsid
- sourced from an implicit session or options.session$readPreference
- defaults to primary or can be configured by options.readPreference$db
- sourced from the name of this databaseIf the client has a serverApi setting:
+apiVersion
apiStrict
apiDeprecationErrors
When in a transaction:
+readConcern
- sourced from readConcern set on the TransactionOptionswriteConcern
- sourced from writeConcern set on the TransactionOptionsAttaching any of the above fields to the command will have no effect as the driver will overwrite the value.
+Create a new collection on a server with the specified options. Use this to create capped collections. +More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
+Collection namespace validation is performed server-side.
+The name of the collection to create
+Optional
options: CreateCollectionOptionsOptional settings for the command
+Creates an index on the db and collection.
+Name of the collection to create the index on.
+Specify the field to index, or an index specification
+Optional
options: CreateIndexesOptionsOptional settings for the command
+Drop a collection from the database, removing it permanently. New accesses will create a new collection.
+Name of collection to drop
+Optional
options: DropCollectionOptionsOptional settings for the command
+Drop a database, removing it permanently from the server.
+Optional
options: CommandOperationOptionsOptional settings for the command
+Retrieves this collections index info.
+The name of the collection.
+Optional settings for the command
+List all collections of this database with optional filter
+Query to filter collections by
+Optional settings for the command
+Optional
filter: DocumentOptional
options: ListCollectionsOptionsRetrieve the current profiling Level for MongoDB
+Optional
options: CommandOperationOptionsOptional settings for the command
+Remove a user from a database
+The username to remove
+Optional
options: CommandOperationOptionsOptional settings for the command
+Rename a collection.
+Name of current collection to rename
+New name of of the collection
+Optional
options: RenameOptionsOptional settings for the command
+A low level cursor API providing basic driver functionality:
+The command that will start a cursor on the server.
+Optional
options: RunCursorCommandOptionsConfigurations for running the command, bson options will apply to getMores
+Set the current profiling level of MongoDB
+The new profiling level (off, slow_only, all).
+Optional
options: CommandOperationOptionsOptional settings for the command
+Get all the db statistics.
+Optional
options: DbStatsOptionsOptional settings for the command
+Create a new Change Stream, watching for new changes (insertions, updates, +replacements, deletions, and invalidations) in this database. Will ignore all +changes to system collections.
+Type of the data being detected by the change stream
+Type of the whole change stream document emitted
+An array of pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
+Optional settings for the command
+watch() accepts two generic arguments for distinct use cases:
+An alias for AbstractCursor.close|AbstractCursor.close().
+Static
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAdd a cursor flag to the cursor
+The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
+The flag boolean value.
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Add a query modifier to the cursor query
+The query modifier (must start with $, such as $orderby etc)
+The modifier value.
+Set the batch size for the cursor.
+The number of documents to return per batch. See command documentation.
+Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
+Set the collation options for the cursor.
+The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
+Get the count of documents for this cursor
+Optional
options: CountOptionsSynchronously 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
+
+
+Rest
...args: Parameters<AbstractCursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Execute the explain for the cursor
+Optional
verbosity: ExplainVerbosityLikeSet the cursor query
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.
Set the cursor hint
+If specified, then the query system will only consider plans using the hinted index.
+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.
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Set the cursor max
+Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
+Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
+Number of milliseconds to wait before aborting the tailed query.
+Set the cursor min
+Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Add a project stage to the aggregation pipeline
+In order to strictly type this function you must provide an interface +that represents the effect of your projection on the result documents.
+By default chaining a projection to your cursor changes the returned type to the generic +Document type. +You should specify a parameterized type to have assertions on your final results.
+// Best way
const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
// Flexible way
const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
+
+
+const cursor: FindCursor<{ a: number; b: string }> = coll.find();
const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
// or always use chaining and save the final cursor
const cursor = coll.find().project<{ a: string }>({
_id: 0,
a: { $convert: { input: '$a', to: 'string' }
}});
+
+
+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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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.
Set the cursor returnKey. +If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. +If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields.
+the returnKey value.
+By default EventEmitter
s 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.
Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection.
+The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
+Sets the sort order of the cursor query.
+The key or keys set for the sort.
+Optional
direction: SortDirectionThe direction of the sorting (1 or -1).
+Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Set the ReadPreference for the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]A builder object that is returned from BulkOperationBase#find. +Is used to build a write operation that involves a query filter.
+Specifies arrayFilters for UpdateOne or UpdateMany bulk operations.
+Specifies the collation for the query condition.
+Add a delete many operation to the bulk operation
+Add a delete one operation to the bulk operation
+Specifies hint for the bulk operation.
+Add a replace one operation to the bulk operation
+Add a multiple update operation to the bulk operation
+Add a single update operation to the bulk operation
+Constructor for a streaming GridFS interface
+Optional
options: GridFSBucketOptionsStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Static
Readonly
INDEXWhen the first call to openUploadStream is made, the upload stream will +check to see if it needs to create the proper indexes on the chunks and +files collections. This event is fired either when 1) it determines that +no index creation is necessary, 2) when it successfully creates the +necessary indexes.
+Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Deletes a file with the given id
+The id of the file doc
+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
+
+
+Rest
...args: Parameters<GridFSBucketEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Convenience wrapper around find on the files collection
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
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()
.
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 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 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 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 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 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 callback function
+Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS.
+Optional
options: GridFSBucketReadStreamOptionsReturns a readable stream (GridFSBucketReadStream) for streaming the
+file with the given name from GridFS. If there are multiple files with
+the same name, this will stream the most recent file with the given name
+(as determined by the uploadDate
field). You can set the revision
+option to change this behavior.
Optional
options: GridFSBucketReadStreamOptionsWithRevisionReturns a writable stream (GridFSBucketWriteStream) for writing +buffers to GridFS. The stream's 'id' property contains the resulting +file's id.
+The value of the 'filename' key in the files doc
+Optional
options: GridFSBucketWriteStreamOptionsOptional settings.
+Returns a writable stream (GridFSBucketWriteStream) for writing +buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting +file's id.
+Optional
options: GridFSBucketWriteStreamOptionsAdds 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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.
Renames the file with the given _id to the given string
+the id of the file to rename
+new name for the file
+By default EventEmitter
s 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.
Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]A readable stream that enables you to read buffers from GridFS.
+Do not instantiate this class directly. Use openDownloadStream()
instead.
Readonly
closedIs true
after 'close'
has been emitted.
Is true
after readable.destroy()
has been called.
Readonly
erroredReturns error if the stream has been destroyed with an error.
+Is true
if it is safe to call read, which means
+the stream has not been destroyed or emitted 'error'
or 'end'
.
Readonly
Experimental
readableReturns whether the stream was destroyed or errored before emitting 'end'
.
Readonly
Experimental
readableReturns whether 'data'
has been emitted.
Readonly
readableGetter for the property encoding
of a given Readable
stream. The encoding
property can be set using the setEncoding method.
Readonly
readableBecomes true
when 'end'
event is emitted.
Readonly
readableThis property reflects the current state of a Readable
stream as described
+in the Three states section.
Readonly
readableReturns the value of highWaterMark
passed when creating this Readable
.
Readonly
readableThis 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
.
Readonly
readableGetter for the property objectMode
of a given Readable
stream.
Static
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Static
Readonly
FILEFires when the stream loaded the file document corresponding to the provided id.
+Optional
_constructOptional
[captureRest
...args: AnyRestEvent emitter +The defined events on documents including:
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Rest
...args: any[]This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form [index, chunk]
. The first index value is 0
and it increases by 1 for each chunk produced.
Optional
options: Pick<ArrayOptions, "signal">a stream of indexed pairs.
+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()
.
Optional
error: ErrorError 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.
+Optional
options: Pick<ArrayOptions, "signal">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
+
+
+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
+
+
+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
+
+
+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
+
+
+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
+
+
+Rest
...args: any[]Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+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
+await
ed 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.
+Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsa promise evaluating to true
if fn returned a truthy value for every one of the chunks.
This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be await
ed.
a function to filter chunks from the stream. Async or not.
+Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsa 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 promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or undefined
if no element was found.
Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsThis 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.
+Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsa 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 await
ed.
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.
+Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsa 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 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.
Optional
options: { Optional
destroyWhen set to false
, calling return
on the async iterator,
+or exiting a for await...of
iteration using a break
, return
, or throw
will not destroy the stream.
+Default: true
.
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
+Optional
listener: FunctionThe 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 await
ed before being passed to the result stream.
a function to map over every chunk in the stream. Async or not.
+Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsa stream mapped with the function fn.
+Alias for emitter.removeListener()
.
Rest
...args: any[]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 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 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 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 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 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 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 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 callback function
+Rest
...args: any[]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 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 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 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 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 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 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 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 callback function
+Rest
...args: any[]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 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 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 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 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 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 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 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 callback function
+Rest
...args: any[]Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Rest
...args: any[]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
size: numberOptional 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.
+Optional
initial: undefinedthe initial value to use in the reduction.
+Optional
options: Pick<ArrayOptions, "signal">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.
Optional
eventName: string | symbolRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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.
Rest
...args: any[]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 EventEmitter
s 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
+await
ed 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.
+Optional
options: Pick<ArrayOptions, "signal">Optional
options: ArrayOptionsa promise evaluating to true
if fn returned a truthy value for at least one of the chunks.
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.
+Optional
options: Pick<ArrayOptions, "signal">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.
const fs = require('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
destination: WritableStreamOptional 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).
const { StringDecoder } = require('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.
Optional
encoding: BufferEncodingEncoding 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.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('node:stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
+
+
+An "old style" readable stream
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
fromA 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.
Optional
options: ReadableOptionsOptions 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
.
Static
fromStatic
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
isStatic
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Static
toA writable stream that enables you to write buffers to GridFS.
+Do not instantiate this class directly. Use openUploadStream()
instead.
Space used to store a chunk currently being inserted
+A Collection instance where the file's chunks are stored
+The number of bytes that each chunk will be limited to
+Readonly
closedIs true
after 'close'
has been emitted.
Is true
after writable.destroy()
has been called.
Indicates the stream is finished uploading
+Readonly
erroredReturns error if the stream has been destroyed with an error.
+The name of the file
+A Collection instance where the file's GridFSFile document is stored
+The document containing information about the inserted file.
+This property is defined after the finish event has been emitted.
+It will remain null
if an error occurs.
The ObjectId used for the _id
field on the GridFSFile document
Accumulates the number of bytes inserted as the stream uploads chunks
+Accumulates the number of chunks inserted as the stream uploads file contents
+Options controlling the metadata inserted along with the file
+Tracks the current offset into the buffered bytes being uploaded
+Contains a number of properties indicating the current state of the stream
+If set the stream was intentionally aborted
+If set an error occurred during insertion
+Indicates the number of chunks that still need to be inserted to exhaust the current buffered data
+If set the stream has ended
+Readonly
writableIs true
if it is safe to call writable.write()
, which means
+the stream has not been destroyed, errored, or ended.
Readonly
writableNumber of times writable.uncork()
needs to be
+called in order to fully uncork the stream.
Readonly
writableIs true
after writable.end()
has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished
instead.
Readonly
writableIs set to true
immediately before the 'finish'
event is emitted.
Readonly
writableReturn the value of highWaterMark
passed when creating this Writable
.
Readonly
writableThis property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark
.
Readonly
writableIs true
if the stream's buffer has been full and stream will emit 'drain'
.
Readonly
writableGetter for the property objectMode
of a given Writable
stream.
Optional
writeThe write concern setting to be used with every insert operation
+Static
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Optional
_writevOptional
[captureRest
...args: AnyRestEvent emitter +The defined events on documents including:
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Rest
...args: any[]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
error: ErrorOptional, 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
+
+
+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
+
+
+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
+
+
+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
+
+
+Rest
...args: any[]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!'.
const fs = require('node:fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
+
+
+Optional
cb: (() => void)Optional
cb: (() => void)Optional
cb: (() => void)Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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
+Optional
listener: FunctionThe 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()
.
Rest
...args: any[]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 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 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 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 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 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 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 callback function
+Rest
...args: any[]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 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 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 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 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 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 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 callback function
+Rest
...args: any[]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 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 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 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 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 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 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 callback function
+Rest
...args: any[]Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Rest
...args: any[]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.
Optional
eventName: string | symbolRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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.
Rest
...args: any[]By default EventEmitter
s 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
.
Optional
callback: ((error: undefined | null | Error) => void)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
.
Optional
callback: ((error: undefined | null | Error) => void)Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
fromStatic
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Static
toStatic
fromStatic
fromStatic
fromOptional
options: ListCollectionsOptionsAn alias for AbstractCursor.close|AbstractCursor.close().
+Optional
optionsStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAdd a cursor flag to the cursor
+The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
+The flag boolean value.
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Set the batch size for the cursor.
+The number of documents to return per batch. See command documentation.
+Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
+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
+
+
+Rest
...args: Parameters<AbstractCursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Set the ReadPreference for the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Optional
options: AbstractCursorOptionsAn alias for AbstractCursor.close|AbstractCursor.close().
+Optional
optionsStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAdd a cursor flag to the cursor
+The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
+The flag boolean value.
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Set the batch size for the cursor.
+The number of documents to return per batch. See command documentation.
+Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
+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
+
+
+Rest
...args: Parameters<AbstractCursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Iterates over all the documents for this cursor using the iterator, callback pattern.
+If the iterator returns false
, iteration will stop.
The iteration callback.
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Set the ReadPreference for the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]An alias for AbstractCursor.close|AbstractCursor.close().
+Readonly
pipelineStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAdd a cursor flag to the cursor
+The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
+The flag boolean value.
+Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Add a stage to the aggregation pipeline
+Set the batch size for the cursor.
+The number of documents to return per batch. See command documentation.
+Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
+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
+
+
+Rest
...args: Parameters<AbstractCursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Execute the explain for the cursor
+Optional
verbosity: ExplainVerbosityLikeIterates over all the documents for this cursor using the iterator, callback pattern.
+If the iterator returns false
, iteration will stop.
The iteration callback.
+Add a geoNear stage to the aggregation pipeline
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.
Add a group stage to the aggregation pipeline
+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.
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] ]
+
+
+Add a lookup stage to the aggregation pipeline
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Add a match stage to the aggregation pipeline
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Add a project stage to the aggregation pipeline
+In order to strictly type this function you must provide an interface +that represents the effect of your projection on the result documents.
+By default chaining a projection to your cursor changes the returned type to the generic Document type. +You should specify a parameterized type to have assertions on your final results.
+// Best way
const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
// Flexible way
const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
+
+
+const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
// or always use chaining and save the final cursor
const cursor = coll.aggregate().project<{ a: string }>({
_id: 0,
a: { $convert: { input: '$a', to: 'string' }
}});
+
+
+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');
+
+
+Add a redact stage to the aggregation pipeline
+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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Add a sort stage to the aggregation pipeline
+Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Add a unwind stage to the aggregation pipeline
+Set the ReadPreference for the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]An error generated when the driver API is used incorrectly
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: { Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A error generated when the user attempts to authenticate +via AWS, but fails
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: { Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A error generated when the user attempts to authenticate +via Azure, but fails.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when a batch command is re-executed after one of the commands in the batch +has failed
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating an unsuccessful Bulk Write
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
codeOptional
connectionOptional
errOptional
errRaw error result document returned by server.
+Optional
okOptional
stackOptional
topologyOptional
writeStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackNumber of documents deleted.
+Legacy name for server error responses
+Number of documents inserted.
+Inserted document generated Id's, hash key is the index of the originating operation
+Number of documents matched for update.
+Number of documents modified.
+Number of documents upserted.
+Upserted document generated Id's, hash key is the index of the originating operation
+An error generated when a ChangeStream operation fails to execute.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+The MongoClient class is a class that allows for making Connections to MongoDB.
+The programmatically provided options take precedence over the URI options.
+import { MongoClient } from 'mongodb';
// Enable command monitoring for debugging
const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });
client.on('commandStarted', started => console.log(started));
client.db().collection('pets');
await client.insertOne({ name: 'spot', kind: 'dog' });
+
+
+Optional
options: MongoClientOptionsAn alias for MongoClient.close().
+Static
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
Cleans up client-side resources used by the MongoCLient and . This includes:
+Force close, emitting no events
+Connect to MongoDB using a url
+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
+
+
+Rest
...args: Parameters<MongoClientEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
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()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Creates a new ClientSession. When using the returned session in an operation +a corresponding ServerSession will be created.
+Optional
options: ClientSessionOptionsCreate a new Change Stream, watching for new changes (insertions, updates, +replacements, deletions, and invalidations) in this cluster. Will ignore all +changes to system collections, as well as the local, admin, and config databases.
+Type of the data being detected by the change stream
+Type of the whole change stream document emitted
+An array of pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
+Optional settings for the command
+watch() accepts two generic arguments for distinct use cases:
+A convenience method for creating and handling the clean up of a ClientSession. +The session will always be ended when the executor finishes.
+An executor function that all operations using the provided session must be invoked in
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
connectConnect to MongoDB using a url
+Optional
options: MongoClientOptionsThe programmatically provided options take precedence over the URI options.
+https://www.mongodb.com/docs/manual/reference/connection-string/
+Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]An error generated when a feature that is not enabled or allowed for the current server +configuration is used
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A representation of the credentials used by MongoDB
+Readonly
mechanismThe method used to authenticate
+Readonly
mechanismSpecial properties used by some types of auth mechanisms
+Readonly
passwordThe password used for authentication
+Readonly
sourceThe database that the user should authenticate against
+Readonly
usernameThe username used for authentication
+Determines if two MongoCredentials objects are equivalent
+If the authentication mechanism is set to "default", resolves the authMechanism +based on the server version and server supported sasl mechanisms.
+A hello response from the server
+Static
mergeAn error indicating that mongodb-client-encryption failed to auto-refresh Azure KMS credentials.
+Do not use this constructor!
+Meant for internal use only.
+Optional
body: DocumentOptional
bodyThe body of the http response that failed, if present.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating that ClientEncryption.createEncryptedCollection()
failed to create data keys
Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating that ClientEncryption.createEncryptedCollection()
failed to create a collection
Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating that something went wrong specifically with MongoDB Client Encryption
+Do not use this constructor!
+Meant for internal use only.
+Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating an invalid argument was provided to an encryption API.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+Do not use this constructor!
+Meant for internal use only.
+Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error thrown when an attempt is made to read from a cursor that has been exhausted
+Do not use this constructor!
+Meant for internal use only.
+Optional
message: stringOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error thrown when the user attempts to add options to a cursor that has already been +initialized
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A class representing a collection's namespace. This class enforces (through Typescript) that
+the collection
portion of the namespace is defined and should only be
+used in scenarios where this can be guaranteed.
Static
fromOptional
namespace: stringCreate a namespace object
+database name
+Optional
collection: stringcollection name
+Static
fromOptional
namespace: stringAn error generated when the driver fails to decompress +data received from the server.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated by the driver
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: { Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: { Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when the user attempts to operate +on a session that has expired or has been closed.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A error generated when the user attempts to authenticate +via GCP, but fails.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when a malformed or invalid chunk is +encountered when reading from a GridFSStream.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when a GridFSStream operation fails to execute.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when the user supplies malformed or unexpected arguments +or when a required argument or field is not provided.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A error generated when the user attempts to authenticate +via Kerberos, but fails to connect to the Kerberos client.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when the user fails to provide authentication credentials before attempting +to connect to a mongo server instance.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when a required module or dependency is not present in the local environment
+Do not use this constructor!
+Meant for internal use only.
+Optional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating an issue with the network, including TCP errors and timeouts.
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: MongoNetworkErrorOptionsOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error indicating a network timeout occurred
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: MongoNetworkErrorOptionsOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error thrown when the user attempts to operate on a database or collection through a MongoClient +that has not yet successfully called the "connect" method
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+A error generated when the user attempts to authenticate +via OIDC callbacks, but fails.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error used when attempting to parse a value (like a connection string)
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when the driver encounters unexpected input +or reaches an unexpected/invalid internal state
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: { Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when an attempt is made to operate +on a closed/closing server.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error coming from the mongo server
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
codeOptional
connectionOptional
errRaw error result document returned by server.
+Optional
okOptional
stackOptional
topologyOptional
writeStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error signifying a client-side server selection error
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
reasonAn optional reason context, such as an error saved during flow of monitoring and selecting servers
+Optional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error signifying a general system issue
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
reasonAn optional reason context, such as an error saved during flow of monitoring and selecting servers
+Optional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error thrown when the user calls a function or method not supported on a tailable cursor
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when an attempt is made to operate on a +dropped, or otherwise unavailable, database.
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when the user makes a mistake in the usage of transactions. +(e.g. attempting to commit a transaction with a readPreference other than primary)
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error generated when a parsable unexpected response comes from the server. +This is generally an error where the driver in a state expecting a certain behavior to occur in +the next message from MongoDB but it receives something else. +This error does not represent an issue with wire message formatting.
+When an operation fails, it is the driver's job to retry it. It must perform serverSelection +again to make sure that it attempts the operation against a server in a good state. If server +selection returns a server that does not support retryable operations, this error is used. +This scenario is unlikely as retryable support would also have been determined on the first attempt +but it is possible the state change could report a selectable server that does not support retries.
+Do not use this constructor!
+Meant for internal use only.
+Optional
options: { Optional
cause?: ErrorOptional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
connectionOptional
stackOptional
topologyStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+An error thrown when the server reports a writeConcernError
+Do not use this constructor!
+Meant for internal use only.
+Optional
causeOptional
codeThis is a number in MongoServerError and a string in MongoDriverError
+Optional
codeOptional
connectionOptional
errRaw error result document returned by server.
+Optional
okThe result document
+Optional
stackOptional
topologyOptional
writeStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackLegacy name for server error responses
+Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. +Returns a builder object used to complete the definition of the operation.
+const bulkOp = collection.initializeOrderedBulkOp();
// Add an updateOne to the bulkOp
bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
// Add an updateMany to the bulkOp
bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
// Add an upsert
bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
// Add a deletion
bulkOp.find({ g: 7 }).deleteOne();
// Add a multi deletion
bulkOp.find({ h: 8 }).delete();
// Add a replaceOne
bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
// Update using a pipeline (requires Mongodb 4.2 or higher)
bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
{ $set: { total: { $sum: [ '$y', '$z' ] } } }
]);
// All of the ops will now be executed
await bulkOp.execute();
+
+
+Add a single insert document to the bulk operation
+The MongoDB ReadConcern, which allows for control of the consistency and isolation properties +of the data read from replica sets and replica set shards.
+Constructs a ReadConcern from the read concern level.
+Static
AVAILABLEStatic
LINEARIZABLEStatic
MAJORITYStatic
SNAPSHOTStatic
fromConstruct a ReadConcern given an options object.
+Optional
options: { The options object from which to extract the write concern.
+Optional
level?: ReadConcernLevelOptional
readThe ReadPreference class is a class that represents a MongoDB ReadPreference and is +used to construct connections.
+A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
+Optional
tags: TagSet[]A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary.
+Optional
options: ReadPreferenceOptionsAdditional read preference options
+Optional
hedgeOptional
maxOptional
minOptional
tagsStatic
nearestStatic
NEARESTStatic
primaryStatic
PRIMARYStatic
PRIMARY_Static
primaryStatic
secondaryStatic
SECONDARYStatic
SECONDARY_Static
secondaryCheck if the two ReadPreferences are equivalent
+The read preference with which to check equality
+Static
fromConstruct a ReadPreference given an options object.
+Optional
options: ReadPreferenceFromOptionsThe options object from which to extract the read preference.
+Static
fromStatic
isStatic
translateReplaces options.readPreference with a ReadPreference instance
+An alias for AbstractCursor.close|AbstractCursor.close().
+Readonly
commandReadonly
getStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
Readonly
CLOSEStatic
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
The cursor is closed and all remaining locally buffered documents have been iterated.
+A killCursors
command was attempted on this cursor.
+This is performed if the cursor id is non zero.
Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
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
+
+
+Rest
...args: Parameters<AbstractCursorEvents[EventKey]>Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Iterates over all the documents for this cursor using the iterator, callback pattern.
+If the iterator returns false
, iteration will stop.
The iteration callback.
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+
+Map all documents using the provided function +If there is a transform set on the cursor, that will be called first and the result passed to +this function's transform.
+Note Cursors use null
internally to indicate that there are no more documents in the cursor. Providing a mapping
+function that maps values to null
will result in the cursor closing itself before it has finished iterating
+all documents. This will not result in a memory leak, just surprising behavior. For example:
const cursor = collection.find({});
cursor.map(() => null);
const documents = await cursor.toArray();
// documents is always [], regardless of how many documents are in the collection.
+
+
+Other falsey values are allowed:
+const cursor = collection.find({});
cursor.map(() => '');
const documents = await cursor.toArray();
// documents is now an array of empty strings
+
+
+Note for Typescript Users: adding a transform changes the return type of the iteration of this cursor, +it does not return a new instance of a cursor. This means when calling map, +you should always assign the result to a new variable in order to get a correctly typed cursor variable. +Take note of the following example:
+const cursor: FindCursor<Document> = coll.find();
const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
+
+
+Alias for emitter.removeListener()
.
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 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 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 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 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 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 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 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 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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Optional
options: CursorStreamOptionsReturns an array of documents. The caller is responsible for making sure that there +is enough memory to store the results. Note that the array only contains partial +results when this cursor had been previously accessed. In that case, +cursor.rewind() can be used to reset the cursor.
+Set the ReadPreference for the cursor.
+The new read preference for the cursor.
+Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Emitted when server is closed.
+The client's view of a single server, based on the most recent hello outcome.
+Internal type, not meant to be directly instantiated
+Optional
$clusterThe minimum measurement of the last 10 measurements of roundTripTime that have been collected
+Is this server data bearing
+Is this server available for reads
+Is this server available for writes
+Determines if another ServerDescription
is equal to this one per the rules defined
+in the spec
Optional
other: null | ServerDescriptionEmitted when server description changes, but does NOT include changes to the RTT.
+The address (host/port pair) of the server
+The new server description
+The previous server description
+A unique identifier for the topology
+Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception.
+Emitted when the server monitor’s hello command is started - immediately before +the hello command is serialized into raw BSON and written to the socket.
+Emitted when the server monitor’s hello succeeds.
+Emitted when server is initialized.
+Optional
options: StreamDescriptionOptionsOptional
__nodejs_Optional
compressorOptional
logicalOptional
maxOptional
minOptional
zlibEmitted when topology is closed.
+Representation of a deployment of servers
+Create a TopologyDescription
+Optional
compatibilityDetermines if this topology description has a data-bearing server available.
+Determines if the topology description has any known servers
+Emitted when topology is initialized.
+A class maintaining state related to a server transaction. Internal Only
+Whether this session is presently in a transaction
+Whether the transaction has started
+Typescript type safe event emitter
+Optional
options: EventEmitterOptionsStatic
captureValue: boolean
+Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
+event. This limit can be changed for individual EventEmitter
instances
+using the emitter.setMaxListeners(n)
method. To change the default
+for allEventEmitter
instances, the events.defaultMaxListeners
property
+can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
+change affects all EventEmitter
instances, including those created before
+the change is made. However, calling emitter.setMaxListeners(n)
still has
+precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
+more listeners to be added but will output a trace warning to stderr indicating
+that a "possible EventEmitter memory leak" has been detected. For any single
+EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
+temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
+
+
+The --trace-warnings
command-line flag can be used to display the
+stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
+have the additional emitter
, type
, and count
properties, referring to
+the event emitter instance, the event's name and the number of attached
+listeners, respectively.
+Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
+regular 'error'
listener is installed.
Optional
[captureRest
...args: AnyRestAlias for emitter.on(eventName, listener)
.
Alias for emitter.on(eventName, listener)
.
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. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Returns the current max listener value for the EventEmitter
which is either
+set by emitter.setMaxListeners(n)
or defaults to 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.
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()
.
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
+
+
+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 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 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
+
+
+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 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 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.
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 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 callback function
+Adds a one-timelistener
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.
Adds a one-timelistener
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 callback function
+Adds a one-timelistener
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 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.
Optional
event: string | symbol | EventKeyRemoves 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener()
will remove the most
+recently added instance. In the example 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 EventEmitter
s 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.
Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation
does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+
+Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
+the emitter.
For EventTarget
s this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
+
+
+Static
getReturns the currently set max amount of listeners.
+For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
+the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+
+Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+
+The emitter to query
+The event name
+Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
+
+
+Returns an AsyncIterator
that iterates eventName
events. It will throw
+if the EventEmitter
emits 'error'
. It removes all listeners when
+exiting the loop. The value
returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+
+Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
+
+
+Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
+event or that is rejected if the EventEmitter
emits 'error'
while waiting.
+The Promise
will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
+semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
+
+
+The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
+'error'
event itself, then it is treated as any other kind of event without
+special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+
+An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+
+Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+
+Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. +Returns a builder object used to complete the definition of the operation.
+const bulkOp = collection.initializeOrderedBulkOp();
// Add an updateOne to the bulkOp
bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
// Add an updateMany to the bulkOp
bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
// Add an upsert
bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
// Add a deletion
bulkOp.find({ g: 7 }).deleteOne();
// Add a multi deletion
bulkOp.find({ h: 8 }).delete();
// Add a replaceOne
bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
// Update using a pipeline (requires Mongodb 4.2 or higher)
bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
{ $set: { total: { $sum: [ '$y', '$z' ] } } }
]);
// All of the ops will now be executed
await bulkOp.execute();
+
+
+Add a single insert document to the bulk operation
+A MongoDB WriteConcern, which describes the level of acknowledgement +requested from MongoDB for write operations.
+Constructs a WriteConcern from the write concern properties.
+Optional
w: Wrequest acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
+Optional
wtimeoutMS: numberspecify a time limit to prevent write operations from blocking indefinitely
+Optional
journal: booleanrequest acknowledgment that the write operation has been written to the on-disk journal
+Optional
fsync: boolean | 1equivalent to the j option. Is deprecated and will be removed in the next major version.
+Optional
fsyncEquivalent to the j option.
+Optional
jRequest acknowledgment that the write operation has been written to the on-disk journal.
+Optional
Readonly
journalRequest acknowledgment that the write operation has been written to the on-disk journal
+Optional
Readonly
wRequest acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
+Optional
wtimeoutSpecify a time limit to prevent write operations from blocking indefinitely.
+Optional
Readonly
wtimeoutMSSpecify a time limit to prevent write operations from blocking indefinitely
+Static
applyApply a write concern to a command document. Will modify and return the command.
+Static
fromConstruct a WriteConcern given an options object.
+Optional
options: WriteConcernOptions | W | WriteConcernOptional
inherit: WriteConcernOptions | WriteConcernAn error representing a failure by the server to apply the requested write concern to the bulk operation.
+Write concern error code.
+Write concern error message.
+An error that occurred during a BulkWrite on the server.
+WriteError code.
+WriteError message.
+WriteError original bulk operation index.
+Calculate the bson size for a passed in Javascript object.
+the Javascript object to calculate the BSON byte size for
+Optional
options: CalculateObjectSizeOptionssize of BSON object in bytes
+Deserialize data as BSON.
+the buffer containing the serialized set of BSON documents.
+Optional
options: DeserializeOptionsreturns the deserialized Javascript Object.
+Deserialize stream data as BSON documents.
+the buffer containing the serialized set of BSON documents.
+the start index in the data Buffer where the deserialization is to start.
+number of documents to deserialize.
+an array where to store the deserialized documents.
+the index in the documents array from where to start inserting documents.
+additional options used for the deserialization.
+next index in the buffer after deserialization x numbers of documents.
+Serialize a Javascript object.
+the Javascript object to serialize.
+Optional
options: SerializeOptionsBuffer object containing the serialized object.
+Serialize a Javascript object using a predefined Buffer and index into the buffer, +useful when pre-allocating the space for serialization.
+the Javascript object to serialize.
+the Buffer you pre-allocated to store the serialized BSON object.
+Optional
options: SerializeOptionsthe index pointing to the last written byte in the buffer.
+Beta
Experimental
Attaches Symbol.asyncDispose
methods to the MongoClient, Cursors, sessions and change streams
+if Symbol.asyncDispose is defined.
It's usually not necessary to call this method - the driver attempts to attach these methods
+itself when its loaded. However, sometimes the driver may be loaded before Symbol.asyncDispose
+is defined, in which case it is necessary to call this method directly. This can happen if the
+application is polyfilling Symbol.asyncDispose
.
Example:
+import { configureExplicitResourceManagement, MongoClient } from 'mongodb/lib/beta';
Symbol.asyncDispose ??= Symbol('dispose');
load();
await using client = new MongoClient(...);
+
+
+The official MongoDB driver for Node.js.
+Upgrading to version 6? Take a look at our upgrade guide here!
+Site | +Link | +
---|---|
Documentation | +www.mongodb.com/docs/drivers/node | +
API Docs | +mongodb.github.io/node-mongodb-native | +
npm package |
+www.npmjs.com/package/mongodb | +
MongoDB | +www.mongodb.com | +
MongoDB University | +learn.mongodb.com | +
MongoDB Developer Center | +www.mongodb.com/developer | +
Stack Overflow | +stackoverflow.com | +
Source Code | +github.com/mongodb/node-mongodb-native | +
Upgrade to v6 | +etc/notes/CHANGES_6.0.0.md | +
Contributing | +CONTRIBUTING.md | +
Changelog | +HISTORY.md | +
Releases are created automatically and signed using the Node team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:
+gpg --import node-driver.asc
+
+
+The GitHub release contains a detached signature file for the NPM package (named
+mongodb-X.Y.Z.tgz.sig
).
The following command returns the link npm package.
+npm view mongodb@vX.Y.Z dist.tarball
+
+
+Using the result of the above command, a curl
command can return the official npm package for the release.
To verify the integrity of the downloaded package, run the following command:
+gpg --verify mongodb-X.Y.Z.tgz.sig mongodb-X.Y.Z.tgz
+
+
+++[!Note] +No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.
+
Think you’ve found a bug? Want to see a new feature in node-mongodb-native
? Please open a
+case in our issue management tool, JIRA:
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are public.
+For issues with, questions about, or feedback for the Node.js driver, please look into our support channels. Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the MongoDB Community Forums.
+Change history can be found in HISTORY.md
.
The driver currently supports 3.6+ servers.
+** 3.6 support is deprecated and support will be removed in a future version **
+For exhaustive server and runtime version compatibility matrices, please refer to the following links:
+ +The following table describes add-on component version compatibility for the Node.js driver. Only packages with versions in these supported ranges are stable when used in combination.
+Component | +mongodb@3.x |
+mongodb@4.x |
+mongodb@5.x |
+mongodb@6.x |
+
---|---|---|---|---|
bson | +^1.0.0 | +^4.0.0 | +^5.0.0 | +^6.0.0 | +
bson-ext | +^1.0.0 || ^2.0.0 | +^4.0.0 | +N/A | +N/A | +
kerberos | +^1.0.0 | +^1.0.0 || ^2.0.0 | +^1.0.0 || ^2.0.0 | +^2.0.1 | +
mongodb-client-encryption | +^1.0.0 | +^1.0.0 || ^2.0.0 | +^2.3.0 | +^6.0.0 | +
mongodb-legacy | +N/A | +^4.0.0 | +^5.0.0 | +^6.0.0 | +
@mongodb-js/zstd | +N/A | +^1.0.0 | +^1.0.0 | +^1.1.0 | +
We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against typescript@4.4.0
.
+This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk.
+Since typescript does not restrict breaking changes to major versions, we consider this support best effort.
+If you run into any unexpected compiler failures against our supported TypeScript versions, please let us know by filing an issue on our JIRA.
The recommended way to get started using the Node.js 5.x driver is by using the npm
(Node Package Manager) to install the dependency in your project.
After you've created your own project using npm init
, you can run:
npm install mongodb
# or ...
yarn add mongodb
+
+
+This will download the MongoDB driver and add a dependency entry in your package.json
file.
If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:
+npm install -D @types/node
+
+
+The MongoDB driver can optionally be enhanced by the following feature packages:
+Maintained by MongoDB:
+Some of these packages include native C++ extensions. +Consult the trouble shooting guide here if you run into compilation issues.
+Third party:
+This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the official documentation.
+package.json
fileFirst, create a directory where your application will live.
+mkdir myProject
cd myProject
+
+
+Enter the following command and answer the questions to create the initial structure for your new project:
+npm init -y
+
+
+Next, install the driver as a dependency.
+npm install mongodb
+
+
+For complete MongoDB installation instructions, see the manual.
+mongod
process.mongod --dbpath=/data
+
+
+You should see the mongod process start up and print some status information.
+Create a new app.js file and add the following code to try out some basic CRUD +operations using the MongoDB driver.
+Add code to connect to the server and the database myProject:
+++NOTE: Resolving DNS Connection issues
+Node.js 18 changed the default DNS resolution ordering from always prioritizing IPv4 to the ordering +returned by the DNS provider. In some environments, this can result in
+localhost
resolving to +an IPv6 address instead of IPv4 and a consequent failure to connect to the server.This can be resolved by:
++
+- specifying the IP address family using the MongoClient
+family
option (MongoClient(<uri>, { family: 4 } )
)- launching mongod or mongos with the ipv6 flag enabled (--ipv6 mongod option documentation)
+- using a host of
+127.0.0.1
in place of localhost- specifying the DNS resolution ordering with the
+--dns-resolution-order
Node.js command line argument (e.g.node --dns-resolution-order=ipv4first
)
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
+
+
+Run your app from the command line with:
+node app.js
+
+
+The application should print Connected successfully to server to the console.
+Add to app.js the following function which uses the insertMany +method to add three documents to the documents collection.
+const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);
+
+
+The insertMany command returns an object with information about the insert operations.
+Add a query that returns all the documents.
+const findResult = await collection.find({}).toArray();
console.log('Found documents =>', findResult);
+
+
+This query returns all the documents in the documents collection. +If you add this below the insertMany example, you'll see the documents you've inserted.
+Add a query filter to find only documents which meet the query criteria.
+const filteredDocs = await collection.find({ a: 3 }).toArray();
console.log('Found documents filtered by { a: 3 } =>', filteredDocs);
+
+
+Only the documents which match 'a' : 3
should be returned.
The following operation updates a document in the documents collection.
+const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });
console.log('Updated documents =>', updateResult);
+
+
+The method updates the first document where the field a is equal to 3 by adding a new field b to the document set to 1. updateResult
contains information about whether there was a matching document to update or not.
Remove the document where the field a is equal to 3.
+const deleteResult = await collection.deleteMany({ a: 3 });
console.log('Deleted documents =>', deleteResult);
+
+
+Indexes can improve your application's +performance. The following function creates an index on the a field in the +documents collection.
+const indexName = await collection.createIndex({ a: 1 });
console.log('index name =', indexName);
+
+
+For more detailed information, see the indexing strategies page.
+If you need to filter certain errors from our driver, we have a helpful tree of errors described in etc/notes/errors.md.
+It is our recommendation to use instanceof
checks on errors and to avoid relying on parsing error.message
and error.name
strings in your code.
+We guarantee instanceof
checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.
+This means instanceof
will always be able to accurately capture the errors that our driver throws.
const client = new MongoClient(url);
await client.connect();
const collection = client.db().collection('collection');
try {
await collection.insertOne({ _id: 1 });
await collection.insertOne({ _id: 1 }); // duplicate key error
} catch (error) {
if (error instanceof MongoServerError) {
console.log(`Error worth logging: ${error}`); // special case for some reason
}
throw error; // still want to crash
}
+
+
+If you need to test with a change from the latest main
branch, our mongodb
npm package has nightly versions released under the nightly
tag.
npm install mongodb@nightly
+
+
+Nightly versions are published regardless of testing outcome. +This means there could be semantic breakages or partially implemented features. +The nightly build is not suitable for production use.
+© 2012-present MongoDB Contributors
+© 2009-2012 Christian Amor Kvalheim
Configuration options for making an AWS encryption key
+The access key used for the AWS KMS provider
+The secret access key used for the AWS KMS provider
+Optional
sessionAn optional AWS session token that will be used as the +X-Amz-Security-Token header for AWS requests.
+Optional
awaitIf awaitData is set to true, when the cursor reaches the end of the capped collection, +MongoDB blocks the query thread for a period of time waiting for new data to arrive. +When new data is inserted into the capped collection, the blocked thread is signaled +to wake up and return the next batch to the client.
+Optional
batchSpecifies the number of documents to return in each response from MongoDB
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxWhen applicable maxAwaitTimeMS
controls the amount of time subsequent getMores
+that a cursor uses to fetch more data should take. (ex. cursor.next())
Optional
maxWhen applicable maxTimeMS
controls the amount of time the initial command
+that constructs a cursor should take. (ex. find, aggregate, listCollections)
Optional
noOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readOptional
readOptional
serializeserialize the javascript functions
+Optional
sessionOptional
tailableBy default, MongoDB will automatically close a cursor when the +client has exhausted all results in the cursor. However, for capped collections +you may use a Tailable Cursor that remains open after the client exhausts +the results in the initial cursor.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
allowallowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
+Optional
authdbOptional
batchThe number of documents to return per batch. See aggregation documentation.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecify collation.
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
cursorReturn the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAdd an index selection hint to an aggregation command
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxThe maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
+Optional
maxspecifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
+Optional
noOptional
omitOptional
outOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
allowallowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
+Optional
authdbOptional
awaitIf awaitData is set to true, when the cursor reaches the end of the capped collection, +MongoDB blocks the query thread for a period of time waiting for new data to arrive. +When new data is inserted into the capped collection, the blocked thread is signaled +to wake up and return the next batch to the client.
+Optional
batchSpecifies the number of documents to return in each response from MongoDB
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecify collation.
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
cursorReturn the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAdd an index selection hint to an aggregation command
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxWhen applicable maxAwaitTimeMS
controls the amount of time subsequent getMores
+that a cursor uses to fetch more data should take. (ex. cursor.next())
Optional
maxWhen applicable maxTimeMS
controls the amount of time the initial command
+that constructs a cursor should take. (ex. find, aggregate, listCollections)
Optional
noOptional
noOptional
omitOptional
outOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
tailableBy default, MongoDB will automatically close a cursor when the +client has exhausted all results in the cursor. However, for capped collections +you may use a Tailable Cursor that remains open after the client exhausts +the results in the initial cursor.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
ALLOWED_Allowed hosts that OIDC auth can connect to.
+Optional
AWS_Optional
CANONICALIZE_Optional
ENVIRONMENTThe OIDC environment. Note that 'test' is for internal use only.
+Optional
OIDC_A user provided OIDC machine callback function.
+Optional
OIDC_A user provided OIDC human interacted callback function.
+Optional
SERVICE_Optional
SERVICE_Optional
SERVICE_Optional
TOKEN_The resource token for OIDC auth in Azure and GCP.
+Optional
bypassAllows the user to bypass auto encryption, maintaining implicit decryption
+Optional
bypassAllows users to bypass query analysis
+Optional
encryptedSupply a schema for the encrypted fields in the document
+Optional
extraOptional
cryptFull path to a MongoDB Crypt shared library to be used (instead of mongocryptd).
+This needs to be the path to the file itself, not a directory.
+It can be an absolute or relative path. If the path is relative and
+its first component is $ORIGIN
, it will be replaced by the directory
+containing the mongodb-client-encryption native addon file. Otherwise,
+the path will be interpreted relative to the current working directory.
Currently, loading different MongoDB Crypt shared library files from different +MongoClients in the same process is not supported.
+If this option is provided and no MongoDB Crypt shared library could be loaded +from the specified location, creating the MongoClient will fail.
+If this option is not provided and cryptSharedLibRequired
is not specified,
+the AutoEncrypter will attempt to spawn and/or use mongocryptd according
+to the mongocryptd-specific extraOptions
options.
Specifying a path prevents mongocryptd from being used as a fallback.
+Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
+Optional
cryptIf specified, never use mongocryptd and instead fail when the MongoDB Crypt +shared library could not be loaded.
+This is always true when cryptSharedLibPath
is specified.
Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
+Optional
mongocryptdIf true, autoEncryption will not attempt to spawn a mongocryptd before connecting
+Optional
mongocryptdCommand line arguments to use when auto-spawning a mongocryptd
+Optional
mongocryptdThe path to the mongocryptd executable on the system
+Optional
mongocryptdURI?: stringA local process the driver communicates with to determine how to encrypt values in a command. +Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise
+Optional
keyA MongoClient
used to fetch keys from a key vault
Optional
keyThe namespace where keys are stored in the key vault
+Optional
kmsConfiguration options that are used by specific KMS providers during key generation, encryption, and decryption.
+Optional
optionsOptional
logger?: ((level: AutoEncryptionLoggerLevel, message: string) => void)An optional hook to catch logging messages from the underlying encryption engine
+Optional
proxyOptional
schemaA map of namespaces to a local JSON schema for encryption
+NOTE: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. +It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. +Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption. +Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
+Optional
tlsThe TLS options to use connecting to the KMS provider
+Configuration options for making an Azure encryption key
+Optional
allowallows the buffer to be larger than the parsed BSON object.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
indexOffset into buffer to begin reading document from
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawOptional
usewhen deserializing a Long return as a BigInt.
+Optional
validationAllows for opt-out utf-8 validation for all keys or +specified keys. Must be all true or all false.
+Optional
checkthe serializer will check if keys are valid.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
indexthe index in the buffer where we wish to start serializing into
+Optional
serializeserialize the javascript functions
+BSON Serialization options.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
serializeserialize the javascript functions
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
forceForce server to assign _id values instead of driver.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
orderedIf true, when an insert fails, don't execute the remaining writes. +If false, continue with remaining inserts when one fails.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Only present when the showExpandedEvents
flag is enabled.
The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+Only present when the showExpandedEvents
flag is enabled.
The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Optional
operationAn description of the operation.
+Only present when the showExpandedEvents
flag is enabled.
Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+For unsharded collections this contains a single field _id
.
+For sharded collections, this will contain all the components of the shard key
Optional
fullContains the pre-image of the modified or deleted document if the +pre-image is available for the change event and either 'required' or +'whenAvailable' was specified for the 'fullDocumentBeforeChange' option +when creating the change stream. If 'whenAvailable' was specified but the +pre-image is unavailable, this will be explicitly set to null.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Namespace the delete event occurred on
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+The database dropped
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Namespace the drop event occurred on
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+Only present when the showExpandedEvents
flag is enabled.
The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Optional
operationAn description of the operation.
+Only present when the showExpandedEvents
flag is enabled.
Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+For unsharded collections this contains a single field _id
.
+For sharded collections, this will contain all the components of the shard key
This key will contain the document being inserted
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Namespace the insert event occurred on
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified.
+Optional
allowallowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
+Optional
authdbOptional
batchThe number of documents to return per batch.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecify collation.
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
cursorReturn the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
fullAllowed values: 'updateLookup', 'whenAvailable', 'required'.
+When set to 'updateLookup', the change notification for partial updates +will include both a delta describing the changes to the document as well +as a copy of the entire document that was changed from some time after +the change occurred.
+When set to 'whenAvailable', configures the change stream to return the +post-image of the modified document for replace and update change events +if the post-image for this event is available.
+When set to 'required', the same behavior as 'whenAvailable' except that +an error is raised if the post-image is not available.
+Optional
fullAllowed values: 'whenAvailable', 'required', 'off'.
+The default is to not send a value, which is equivalent to 'off'.
+When set to 'whenAvailable', configures the change stream to return the +pre-image of the modified document for replace, update, and delete change +events if it is available.
+When set to 'required', the same behavior as 'whenAvailable' except that +an error is raised if the pre-image is not available.
+Optional
hintAdd an index selection hint to an aggregation command
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxThe maximum amount of time for the server to wait on new documents to satisfy a change stream query.
+Optional
maxspecifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
+Optional
noOptional
omitOptional
outOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
resumeAllows you to start a changeStream after a specified event.
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
showWhen enabled, configures the change stream to include extra change events.
+Optional
startSimilar to resumeAfter, but will allow you to start after an invalidated event.
+Optional
startWill start the changeStream after the specified operationTime.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willThe id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Optional
operationAn description of the operation.
+Only present when the showExpandedEvents
flag is enabled.
Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+The "from" namespace that the rename occurred on
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+The new name for the ns.coll
collection
Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+For unsharded collections this contains a single field _id
.
+For sharded collections, this will contain all the components of the shard key
The fullDocument of a replace event represents the document after the insert of the replacement document
+Optional
fullContains the pre-image of the modified or deleted document if the +pre-image is available for the change event and either 'required' or +'whenAvailable' was specified for the 'fullDocumentBeforeChange' option +when creating the change stream. If 'whenAvailable' was specified but the +pre-image is unavailable, this will be explicitly set to null.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Namespace the replace event occurred on
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Optional
operationAn description of the operation.
+Only present when the showExpandedEvents
flag is enabled.
Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Optional
operationAn description of the operation.
+Only present when the showExpandedEvents
flag is enabled.
Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+The id functions as an opaque token for use when resuming an interrupted +change stream.
+Optional
clusterThe timestamp from the oplog entry associated with the event. +For events that happened as part of a multi-document transaction, the associated change stream +notifications will have the same clusterTime value, namely the time when the transaction was committed. +On a sharded cluster, events that occur on different shards can have the same clusterTime but be +associated with different transactions or even not be associated with any transaction. +To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
+The UUID (Binary subtype 4) of the collection that the operation was performed on.
+Only present when the showExpandedEvents
flag is enabled.
NOTE: collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers +flag is enabled.
+For unsharded collections this contains a single field _id
.
+For sharded collections, this will contain all the components of the shard key
Optional
fullThis is only set if fullDocument
is set to 'updateLookup'
+Contains the point-in-time post-image of the modified document if the
+post-image is available and either 'required' or 'whenAvailable' was
+specified for the 'fullDocument' option when creating the change stream.
Optional
fullContains the pre-image of the modified or deleted document if the +pre-image is available for the change event and either 'required' or +'whenAvailable' was specified for the 'fullDocumentBeforeChange' option +when creating the change stream. If 'whenAvailable' was specified but the +pre-image is unavailable, this will be explicitly set to null.
+Optional
lsidThe identifier for the session associated with the transaction. +Only present if the operation is part of a multi-document transaction.
+Namespace the update event occurred on
+Describes the type of operation represented in this change notification
+Optional
splitWhen the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent +stage, events larger than 16MB will be split into multiple events and contain the +following information about which fragment the current event is.
+Optional
txnThe transaction number. +Only present if the operation is part of a multi-document transaction.
+NOTE: txnNumber can be a Long if promoteLongs is set to false
+Contains a description of updated and removed fields in this operation
+Options to provide when creating a new data key.
+Optional
keyAn optional list of string alternate names used to reference a key. +If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id.
+Optional
Experimental
keyOptional
masterIdentifies a new KMS-specific key used to encrypt the new data key
+Options to provide when encrypting data.
+The algorithm to use for encryption.
+Optional
contentionThe contention factor.
+Optional
keyA unique string name corresponding to an already existing dataKey.
+Optional
keyThe id of the Binary dataKey to use for encryption
+Optional
queryThe query type.
+Optional
rangeThe index options for a Queryable Encryption field supporting "range" queries.
+Additional settings to provide when creating a new ClientEncryption
instance.
Optional
keyA MongoClient used to fetch keys from a key vault. Defaults to client.
+The namespace of the key vault, used to store encryption keys
+Optional
kmsOptions for specific KMS providers to use
+Optional
proxyOptions for specifying a Socks5 proxy to use for connecting to the KMS.
+Optional
tlsTLS options for kms providers to use.
+Experimental
Optional
applicationOptional
envFaaS environment information
+Optional
causalWhether causal consistency should be enabled on this session
+Optional
defaultThe default TransactionOptions to use for transactions started on this session.
+Optional
snapshotWhether all read operations should be read from the same snapshot for this session (NOTE: not compatible with causalConsistency=true
)
Gossiped in component for the cluster time tracking the state of user databases +across the cluster. It may optionally include a signature identifying the process that +generated such a value.
+Optional
alternateOptional
backwardsOptional
caseOptional
caseOptional
maxOptional
normalizationOptional
numericOptional
strengthOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
+Optional
serializeserialize the javascript functions
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
allowOptional
ALPNProtocolsAn array of strings or a Buffer naming possible ALPN protocols. +(Protocols should be ordered by their priority.)
+Optional
autoOptional
autoOptional
caOptionally override the trusted CA certificates. Default is to trust +the well-known CAs curated by Mozilla. Mozilla's CAs are completely +replaced when CAs are explicitly specified using this option.
+Optional
cancellationOptional
certCert chains in PEM format. One cert chain should be provided per +private key. Each cert chain should consist of the PEM formatted +certificate for a provided private key, followed by the PEM +formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, +see ca). When providing multiple cert chains, they do not have to +be in the same order as their private keys in key. If the +intermediate certificates are not provided, the peer will not be +able to validate the certificate, and the handshake will fail.
+Optional
checkVerifies the certificate cert
is issued to hostname
.
Returns Error object, populating it with reason
, host
, and cert
on
+failure. On success, returns undefined.
This function is intended to be used in combination with thecheckServerIdentity
option that can be passed to connect and as
+such operates on a certificate object
. For other purposes, consider using x509.checkHost()
instead.
This function can be overwritten by providing an alternative function as the options.checkServerIdentity
option that is passed to tls.connect()
. The
+overwriting function can call tls.checkServerIdentity()
of course, to augment
+the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as
+being issued by trusted CA (options.ca
).
Earlier versions of Node.js incorrectly accepted certificates for a givenhostname
if a matching uniformResourceIdentifier
subject alternative name
+was present (see CVE-2021-44531). Applications that wish to acceptuniformResourceIdentifier
subject alternative names can use
+a custom options.checkServerIdentity
function that implements the desired behavior.
The host name or IP address to verify the certificate against.
+A certificate object
representing the peer's certificate.
Optional
ciphersCipher suite specification, replacing the default. For more +information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
+Optional
compressorsOptional
connectOptional
credentialsOptional
crlPEM formatted CRLs (Certificate Revocation Lists).
+Optional
ecdhA string describing a named curve or a colon separated list of curve +NIDs or names, for example P-521:P-384:P-256, to use for ECDH key +agreement. Set to auto to select the curve automatically. Use +crypto.getCurves() to obtain a list of available curve names. On +recent releases, openssl ecparam -list_curves will also display the +name and description of each available elliptic curve. Default: +tls.DEFAULT_ECDH_CURVE.
+Optional
familyOptional
hintsOptional
keyPrivate keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase:
Optional
localOptional
localOptional
logicalOptional
lookupOptional
minDHSizeOptional
noOptional
passphraseShared passphrase used for a single private key and/or a PFX.
+Optional
pfxPFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase:
Optional
proxyOptional
proxyOptional
proxyOptional
proxyOptional
rejectIf true the server will reject any connection which is not +authorized with the list of supplied CAs. This option only has an +effect if requestCert is true.
+Optional
secureAn optional TLS context object from tls.createSecureContext()
+Optional
secureLegacy mechanism to select the TLS protocol version to use, it does +not support independent control of the minimum and maximum version, +and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow +any TLS protocol version up to TLSv1.3. It is not recommended to use +TLS versions less than 1.2, but it may be required for +interoperability. Default: none, see minVersion.
+Optional
serverOptional
servernameOptional
sessionAn optional Buffer instance containing a TLS session.
+Optional
socketOptional
allowOptional
ALPNProtocolsAn array of strings or a Buffer naming possible ALPN protocols. +(Protocols should be ordered by their priority.)
+Optional
autoOptional
autoOptional
caOptionally override the trusted CA certificates. Default is to trust +the well-known CAs curated by Mozilla. Mozilla's CAs are completely +replaced when CAs are explicitly specified using this option.
+Optional
cancellationOptional
certCert chains in PEM format. One cert chain should be provided per +private key. Each cert chain should consist of the PEM formatted +certificate for a provided private key, followed by the PEM +formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, +see ca). When providing multiple cert chains, they do not have to +be in the same order as their private keys in key. If the +intermediate certificates are not provided, the peer will not be +able to validate the certificate, and the handshake will fail.
+Optional
checkVerifies the certificate cert
is issued to hostname
.
Returns Error object, populating it with reason
, host
, and cert
on
+failure. On success, returns undefined.
This function is intended to be used in combination with thecheckServerIdentity
option that can be passed to connect and as
+such operates on a certificate object
. For other purposes, consider using x509.checkHost()
instead.
This function can be overwritten by providing an alternative function as the options.checkServerIdentity
option that is passed to tls.connect()
. The
+overwriting function can call tls.checkServerIdentity()
of course, to augment
+the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as
+being issued by trusted CA (options.ca
).
Earlier versions of Node.js incorrectly accepted certificates for a givenhostname
if a matching uniformResourceIdentifier
subject alternative name
+was present (see CVE-2021-44531). Applications that wish to acceptuniformResourceIdentifier
subject alternative names can use
+a custom options.checkServerIdentity
function that implements the desired behavior.
The host name or IP address to verify the certificate against.
+A certificate object
representing the peer's certificate.
Optional
ciphersCipher suite specification, replacing the default. For more +information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
+Optional
compressorsOptional
connectOptional
credentialsOptional
crlPEM formatted CRLs (Certificate Revocation Lists).
+Optional
ecdhA string describing a named curve or a colon separated list of curve +NIDs or names, for example P-521:P-384:P-256, to use for ECDH key +agreement. Set to auto to select the curve automatically. Use +crypto.getCurves() to obtain a list of available curve names. On +recent releases, openssl ecparam -list_curves will also display the +name and description of each available elliptic curve. Default: +tls.DEFAULT_ECDH_CURVE.
+Optional
familyOptional
hintsOptional
keyPrivate keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase:
If we are in load balancer mode.
+Optional
localOptional
localOptional
logicalOptional
lookupThe maximum number of connections that may be in the process of being established concurrently by the connection pool.
+The maximum amount of time a connection should remain idle in the connection pool before being marked idle.
+The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.
+Optional
minDHSizeThe minimum number of connections that MUST exist at any moment in a single connection pool.
+Optional
noOptional
passphraseShared passphrase used for a single private key and/or a PFX.
+Optional
pfxPFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase:
Optional
proxyOptional
proxyOptional
proxyOptional
proxyOptional
rejectIf true the server will reject any connection which is not +authorized with the list of supplied CAs. This option only has an +effect if requestCert is true.
+Optional
secureAn optional TLS context object from tls.createSecureContext()
+Optional
secureLegacy mechanism to select the TLS protocol version to use, it does +not support independent control of the minimum and maximum version, +and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow +any TLS protocol version up to TLSv1.3. It is not recommended to use +TLS versions less than 1.2, but it may be required for +interoperability. Default: none, see minVersion.
+Optional
serverOptional
servernameOptional
sessionAn optional Buffer instance containing a TLS session.
+Optional
socketThe maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.
+Optional
allowallowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
+Optional
authdbOptional
batchThe number of documents to return per batch. See aggregation documentation.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecify collation.
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
cursorReturn the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAdd an index selection hint to an aggregation command
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
limitThe maximum amount of documents to consider.
+Optional
maxThe maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
+Optional
maxspecifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
+Optional
noOptional
omitOptional
outOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
skipThe number of documents to skip.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAn index name hint for the query.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
limitThe maximum amounts to count before aborting.
+Optional
maxNumber of milliseconds to wait before aborting the query.
+Optional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
skipThe number of documents to skip.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
authdbOptional
autoOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
cappedCreate a capped collection
+Optional
changeIf set, enables pre-update and post-update document events to be included for any +change streams that listen on this collection.
+Optional
checkthe serializer will check if keys are valid.
+Optional
clusteredA document specifying configuration options for clustered collections. For MongoDB 5.3 and above.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
Experimental
encryptedOptional
expireThe number of seconds after which a document in a timeseries or clustered collection expires.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
flagsAvailable for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
indexAllows users to specify a default configuration for indexes when creating a collection
+Optional
maxThe maximum number of documents in the capped collection
+Optional
maxOptional
noOptional
omitOptional
pipelineAn array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view
+Optional
pkA primary key factory function for generation of custom _id keys.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
sizeThe size of the capped collection in bytes
+Optional
storageAllows users to specify configuration to the storage engine on a per-collection basis when creating a collection
+Optional
timeseriesA document specifying configuration options for timeseries collections.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
validationDetermines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted
+Optional
validationDetermines how strictly MongoDB applies the validation rules to existing documents during an update
+Optional
validatorAllows users to specify validation rules or expressions for the collection. For more information, see Document Validation
+Optional
viewThe name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view (i.e., does not include the database name and implies the same database as the view to create)
+Optional
willOptional
writeWrite Concern as an object
+Optional
2dsphereOptional
authdbOptional
backgroundCreates the index in the background, yielding whenever possible.
+Optional
bitsOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bucketOptional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
commit(MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes.
+Optional
dbOptional
default_Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
expireAllows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hiddenSpecifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher)
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
language_Optional
maxFor geospatial indexes set the high bound for the co-ordinates.
+Optional
maxOptional
minFor geospatial indexes set the lower bound for the co-ordinates.
+Optional
nameOverride the autogenerated index name (useful if the resulting name is larger than 128 bytes)
+Optional
noOptional
omitOptional
partialCreates a partial index based on the given filter object (MongoDB 3.2 or higher)
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
sparseCreates a sparse index.
+Optional
storageAllows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher)
+Optional
textOptional
uniqueCreates an unique index.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
versionSpecifies the index version number, either 0 or 1.
+Optional
weightsOptional
wildcardOptional
willThe schema for a DataKey in the key vault collection.
+Optional
authIf the database authentication is dependent on another databaseName.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
forceForce server to assign _id values instead of driver.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
pkA primary key factory object for generation of custom _id keys.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
scaleDivide the returned sizes by scale value.
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecifies the collation to use for the operation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintSpecify that the update query should only consider plans using the hinted index
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
orderedIf true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
Experimental
encryptedOptional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxThe maximum amount of time to allow the operation to run.
+This option is sent only if the caller explicitly provides a value. The default is to not send a value.
+Optional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
__idOptional
$allOptional
$bitsOptional
$bitsOptional
$bitsOptional
$bitsOptional
$elemOptional
$eqOptional
$existsWhen true
, $exists
matches the documents that contain the field,
+including documents where the field value is null.
Optional
$exprOptional
$geoOptional
$geoOptional
$gtOptional
$gteOptional
$inOptional
$jsonOptional
$ltOptional
$lteOptional
$maxOptional
$modOptional
$neOptional
$nearOptional
$nearOptional
$ninOptional
$notOptional
$optionsOptional
$randOptional
$regexOptional
$sizeOptional
$typeOptional
idOptional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAn optional hint for query optimization. See the command reference for more information.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
includeReturn the ModifyResult instead of the modified document. Defaults to false
+Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
projectionLimits the fields to return for all matching documents.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
sortDetermines which document the operation modifies if the query selects multiple documents.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAn optional hint for query optimization. See the command reference for more information.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
includeReturn the ModifyResult instead of the modified document. Defaults to false
+Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
projectionLimits the fields to return for all matching documents.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
returnWhen set to 'after', returns the updated document rather than the original. The default is 'before'.
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
sortDetermines which document the operation modifies if the query selects multiple documents.
+Optional
upsertUpsert the document if it does not exist.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
arrayOptional list of array filters referenced in filtered positional operators
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintAn optional hint for query optimization. See the command reference for more information.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
includeReturn the ModifyResult instead of the modified document. Defaults to false
+Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
projectionLimits the fields to return for all matching documents.
+Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
returnWhen set to 'after', returns the updated document rather than the original. The default is 'before'.
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
sortDetermines which document the operation modifies if the query selects multiple documents.
+Optional
upsertUpsert the document if it does not exist.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
allowAllows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher)
+Optional
allowFor queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable.
+Optional
authdbOptional
awaitSpecify if the cursor is a tailable-await cursor. Requires tailable
to be true
Optional
batchSet the batchSize for the getMoreCommand when iterating over the query results.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintTell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
limitSets the limit of documents returned in the query.
+Optional
maxThe exclusive upper bound for a specific index
+Optional
maxThe maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires tailable
and awaitData
to be true
Optional
maxNumber of milliseconds to wait before aborting the query.
+Optional
minThe inclusive lower bound for a specific index
+Optional
noThe server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that.
+Optional
noOptional
omitOptional
oplogOption to enable an optimized code path for queries looking for a particular range of ts
values in the oplog. Requires tailable
to be true.
Optional
projectionThe fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1}
or {'a': 0, 'b': 0}
Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
returnIf true, returns only the index keys in the resulting documents.
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
showDetermines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents.
+Optional
singleDetermines whether to close the cursor after the first batch. Defaults to false.
+Optional
skipSet to skip N documents ahead in your query (useful for pagination).
+Optional
sortSet to sort the documents coming back from the query. Array of indexes, [['a', 1]]
etc.
Optional
tailableSpecify if the cursor is tailable.
+Optional
timeoutSpecify if the cursor can timeout.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willConfiguration options for making an AWS encryption key
+Optional
endpointKMS URL, defaults to https://www.googleapis.com/auth/cloudkms
Key name
+Key ring name
+Optional
keyKey version
+Location name (e.g. "global")
+GCP project ID
+Optional
bucketThe 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot.
+Optional
chunkNumber of bytes stored in each chunk. Defaults to 255KB
+Optional
readRead preference to be passed to read operations
+Optional
writeWrite Concern as an object
+Optional
end0-indexed non-negative byte offset to the end of the file contents
+to be returned by the stream. end
is non-inclusive
Optional
revisionThe revision number relative to the oldest file with the given filename. 0 +gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the +newest.
+Optional
skipOptional
sortOptional
start0-indexed non-negative byte offset from the beginning of the file
+Optional
aliasesArray of strings to store in the file document's aliases
field.
Optional
chunkOverwrite this bucket's chunkSizeBytes for this file
+Optional
contentString to store in the file document's contentType
field.
Optional
idCustom file id for the GridFS file.
+Optional
metadataObject to store in the file document's metadata
field
Optional
writeWrite Concern as an object
+The information returned by the server on the IDP server.
+A unique client ID for this OIDC client.
+A URL which describes the Authentication Server. This identifier should +be the iss of provided access tokens, and be viable for RFC8414 metadata +discovery and RFC9207 identification.
+Optional
requestA list of additional scopes to request from IdP.
+The response from the IdP server with the access token and +optional expiration time and refresh token.
+The OIDC access token.
+Optional
expiresThe time when the access token expires. For future use.
+Optional
refreshThe refresh token, if applicable, to be used by the callback to request a new token from the issuer.
+Optional
2dsphereOptional
backgroundCreates the index in the background, yielding whenever possible.
+Optional
bitsOptional
bucketOptional
collationOptional
default_Optional
expireAllows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
+Optional
hiddenSpecifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher)
+Optional
language_Optional
maxFor geospatial indexes set the high bound for the co-ordinates.
+Optional
minFor geospatial indexes set the lower bound for the co-ordinates.
+Optional
nameOptional
partialCreates a partial index based on the given filter object (MongoDB 3.2 or higher)
+Optional
sparseCreates a sparse index.
+Optional
storageAllows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher)
+Optional
textOptional
uniqueCreates an unique index.
+Optional
versionSpecifies the index version number, either 0 or 1.
+Optional
weightsOptional
wildcardOptional
awaitIf awaitData is set to true, when the cursor reaches the end of the capped collection, +MongoDB blocks the query thread for a period of time waiting for new data to arrive. +When new data is inserted into the capped collection, the blocked thread is signaled +to wake up and return the next batch to the client.
+Optional
batchSpecifies the number of documents to return in each response from MongoDB
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
fullWhen true
, an array of index descriptions is returned.
+When false
, the driver returns an object that with keys corresponding to index names with values
+corresponding to the entries of the indexes' key.
For example, the given the following indexes:
+[ { name: 'a_1', key: { a: 1 } }, { name: 'b_1_c_1' , key: { b: 1, c: 1 } }]
+
+
+When full
is true
, the above array is returned. When full
is false
, the following is returned:
{
'a_1': [['a', 1]],
'b_1_c_1': [['b', 1], ['c', 1]],
}
+
+
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxWhen applicable maxAwaitTimeMS
controls the amount of time subsequent getMores
+that a cursor uses to fetch more data should take. (ex. cursor.next())
Optional
maxWhen applicable maxTimeMS
controls the amount of time the initial command
+that constructs a cursor should take. (ex. find, aggregate, listCollections)
Optional
noOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readOptional
readOptional
serializeserialize the javascript functions
+Optional
sessionOptional
tailableBy default, MongoDB will automatically close a cursor when the +client has exhausted all results in the cursor. However, for capped collections +you may use a Tailable Cursor that remains open after the client exhausts +the results in the initial cursor.
+Optional
usewhen deserializing a Long return as a BigInt.
+Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined
+The number of inserted documents for this operations
+Map of the index of the inserted document to the id of the inserted document
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassAllow driver to bypass schema validation.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
forceForce server to assign _id values instead of driver.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined
+The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data
+Configuration options for making a KMIP encryption key
+Optional
delegatedIf true, this key should be decrypted by the KMIP server.
+Requires mongodb-client-encryption>=6.0.1
.
Optional
endpointHost with optional port.
+Optional
keykeyId is the KMIP Unique Identifier to a 96 byte KMIP Secret Data managed object.
+If keyId is omitted, a random 96 byte KMIP Secret Data managed object will be created.
+Optional
endpointThe output endpoint string. +The endpoint consists of a hostname and port separated by a colon. +E.g. "example.com:123". A port is always present.
+Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.
+Named KMS providers are not supported for automatic KMS credential fetching.
+Optional
awsConfiguration options for using 'aws' as your KMS provider
+Optional
azureConfiguration options for using 'azure' as your KMS provider
+Optional
gcpConfiguration options for using 'gcp' as your KMS provider
+Optional
kmipConfiguration options for using 'kmip' as your KMS provider
+Optional
localConfiguration options for using 'local' as your KMS provider
+Optional
authdbOptional
authorizedSince 4.0: If true and nameOnly is true, allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced.
+Optional
batchThe batchSize for the returned command cursor or if pre 2.8 the systems batch collection
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
nameSince 4.0: If true, will only return the collection name in the response, and will omit additional info
+Optional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
authdbOptional
authorizedA flag that determines which databases are returned based on the user privileges when access control is enabled
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
filterA query predicate that determines which databases are listed
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
nameA flag to indicate whether the command should return just the database names, or return both database names and size information
+Optional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Describes all possible URI query options for the mongo client
+Optional
allowOptional
ALPNProtocolsAn array of strings or a Buffer naming possible ALPN protocols. +(Protocols should be ordered by their priority.)
+Optional
appThe name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections
+Optional
authThe auth settings for when connection to server.
+Optional
authSpecify the authentication mechanism that MongoDB will use to authenticate the connection.
+Optional
authSpecify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs.
+Optional
authSpecify the database name associated with the user’s credentials.
+Optional
autoOptionally enable in-use auto encryption
+Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error +(see libmongocrypt: Auto Encryption Allow-List). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
+Automatic encryption requires the authenticated user to have the listCollections privilege action.
+If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
+If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
+Optional
autoOptional
autoOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
caOptionally override the trusted CA certificates. Default is to trust +the well-known CAs curated by Mozilla. Mozilla's CAs are completely +replaced when CAs are explicitly specified using this option.
+Optional
certCert chains in PEM format. One cert chain should be provided per +private key. Each cert chain should consist of the PEM formatted +certificate for a provided private key, followed by the PEM +formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, +see ca). When providing multiple cert chains, they do not have to +be in the same order as their private keys in key. If the +intermediate certificates are not provided, the peer will not be +able to validate the certificate, and the handshake will fail.
+Optional
checkthe serializer will check if keys are valid.
+Optional
checkVerifies the certificate cert
is issued to hostname
.
Returns Error object, populating it with reason
, host
, and cert
on
+failure. On success, returns undefined.
This function is intended to be used in combination with thecheckServerIdentity
option that can be passed to connect and as
+such operates on a certificate object
. For other purposes, consider using x509.checkHost()
instead.
This function can be overwritten by providing an alternative function as the options.checkServerIdentity
option that is passed to tls.connect()
. The
+overwriting function can call tls.checkServerIdentity()
of course, to augment
+the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as
+being issued by trusted CA (options.ca
).
Earlier versions of Node.js incorrectly accepted certificates for a givenhostname
if a matching uniformResourceIdentifier
subject alternative name
+was present (see CVE-2021-44531). Applications that wish to acceptuniformResourceIdentifier
subject alternative names can use
+a custom options.checkServerIdentity
function that implements the desired behavior.
The host name or IP address to verify the certificate against.
+A certificate object
representing the peer's certificate.
Optional
ciphersCipher suite specification, replacing the default. For more +information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
+Optional
compressorsAn array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance.
+Optional
connectThe time in milliseconds to attempt a connection before timing out.
+Optional
crlPEM formatted CRLs (Certificate Revocation Lists).
+Optional
directAllow a driver to force a Single topology type with a connection string containing one host
+Optional
driverAllows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
+Optional
ecdhA string describing a named curve or a colon separated list of curve +NIDs or names, for example P-521:P-384:P-256, to use for ECDH key +agreement. Set to auto to select the curve automatically. Use +crypto.getCurves() to obtain a list of available curve names. On +recent releases, openssl ecparam -list_curves will also display the +name and description of each available elliptic curve. Default: +tls.DEFAULT_ECDH_CURVE.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
familyOptional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
forceForce server to assign _id
values instead of driver
Optional
heartbeatheartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one.
+Optional
hintsOptional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
journalThe journal write concern
+Optional
keyPrivate keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase:
Optional
loadInstruct the driver it is connecting to a load balancer fronting a mongos like service
+Optional
localOptional
localOptional
localThe size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances.
+Optional
lookupOptional
maxThe maximum number of connections that may be in the process of being established concurrently by the connection pool.
+Optional
maxThe maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed.
+Optional
maxThe maximum number of connections in the connection pool.
+Optional
maxSpecifies, in seconds, how stale a secondary can be before the client stops using it for read operations.
+Optional
minDHSizeOptional
minSets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort.
+Optional
minThe minimum number of connections in the connection pool.
+Optional
monitorEnable command monitoring for this client
+Optional
noTCP Connection no delay
+Optional
passphraseShared passphrase used for a single private key and/or a PFX.
+Optional
pfxPFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase:
Optional
pkA primary key factory function for generation of custom _id
keys
Optional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
proxyConfigures a Socks5 proxy host used for creating TCP connections.
+Optional
proxyConfigures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication.
+Optional
proxyConfigures a Socks5 proxy port used for creating TCP connections.
+Optional
proxyConfigures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern for the collection (only MongoDB 3.2 or higher supported)
+Optional
readThe level of isolation
+Optional
readSpecifies the read preferences for this connection
+Optional
readSpecifies the tags document as a comma-separated list of colon-separated key-value pairs.
+Optional
rejectIf true the server will reject any connection which is not +authorized with the list of supplied CAs. This option only has an +effect if requestCert is true.
+Optional
replicaSpecifies the name of the replica set, if the mongod is a member of a replica set.
+Optional
retryEnables retryable reads.
+Optional
retryEnable retryable writes.
+Optional
secureAn optional TLS context object from tls.createSecureContext()
+Optional
secureLegacy mechanism to select the TLS protocol version to use, it does +not support independent control of the minimum and maximum version, +and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow +any TLS protocol version up to TLSv1.3. It is not recommended to use +TLS versions less than 1.2, but it may be required for +interoperability. Default: none, see minVersion.
+Optional
serializeserialize the javascript functions
+Optional
serverServer API version
+Optional
serverInstructs the driver monitors to use a specific monitoring mode
+Optional
servernameOptional
serverSpecifies how long (in milliseconds) to block for server selection before throwing an exception.
+Optional
sessionAn optional Buffer instance containing a TLS session.
+Optional
socketThe time in milliseconds to attempt a send or receive on a socket before the attempt times out.
+Optional
srvThe maximum number of hosts to connect to when using an srv connection string, a setting of 0
means unlimited hosts
Optional
srvModifies the srv URI to look like:
+_{srvServiceName}._tcp.{hostname}.{domainname}
Querying this DNS URI is expected to respond with SRV records
+Optional
sslA boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.)
+Optional
tlsEnables or disables TLS/SSL for the connection.
+Optional
tlsBypasses validation of the certificates presented by the mongod/mongos instance
+Optional
tlsDisables hostname validation of the certificate presented by the mongod/mongos instance.
+Optional
tlsCAFileSpecifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance.
+Optional
tlsSpecifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key.
+Optional
tlsSpecifies the password to de-crypt the tlsCertificateKeyFile.
+Optional
tlsCRLFileSpecifies the location of a local CRL .pem file that contains the client revokation list.
+Optional
tlsDisables various certificate validations.
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
wThe write concern w value
+Optional
waitThe maximum time in milliseconds that a thread can wait for a connection to become available.
+Optional
writeA MongoDB WriteConcern, which describes the level of acknowledgement +requested from MongoDB for write operations.
+Optional
wtimeoutMSThe write concern timeout
+Optional
zlibAn integer that specifies the compression level if using zlib for network compression.
+Parsed Mongo Client Options.
+User supplied options are documented by MongoClientOptions
.
NOTE: The client's options parsing is subject to change to support new features. +This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically.
+Options are sourced from:
+Not all options may be present after client construction as some are obtained from asynchronous operations.
+Optional
allowOptional
ALPNProtocolsAn array of strings or a Buffer naming possible ALPN protocols. +(Protocols should be ordered by their priority.)
+Optional
appOptionally enable in-use auto encryption
+Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error +(see libmongocrypt: Auto Encryption Allow-List). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
+Automatic encryption requires the authenticated user to have the listCollections privilege action.
+If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
+If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
+Optional
autoOptional
autoOptional
caOptionally override the trusted CA certificates. Default is to trust +the well-known CAs curated by Mozilla. Mozilla's CAs are completely +replaced when CAs are explicitly specified using this option.
+Optional
certCert chains in PEM format. One cert chain should be provided per +private key. Each cert chain should consist of the PEM formatted +certificate for a provided private key, followed by the PEM +formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, +see ca). When providing multiple cert chains, they do not have to +be in the same order as their private keys in key. If the +intermediate certificates are not provided, the peer will not be +able to validate the certificate, and the handshake will fail.
+Optional
checkVerifies the certificate cert
is issued to hostname
.
Returns Error object, populating it with reason
, host
, and cert
on
+failure. On success, returns undefined.
This function is intended to be used in combination with thecheckServerIdentity
option that can be passed to connect and as
+such operates on a certificate object
. For other purposes, consider using x509.checkHost()
instead.
This function can be overwritten by providing an alternative function as the options.checkServerIdentity
option that is passed to tls.connect()
. The
+overwriting function can call tls.checkServerIdentity()
of course, to augment
+the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as
+being issued by trusted CA (options.ca
).
Earlier versions of Node.js incorrectly accepted certificates for a givenhostname
if a matching uniformResourceIdentifier
subject alternative name
+was present (see CVE-2021-44531). Applications that wish to acceptuniformResourceIdentifier
subject alternative names can use
+a custom options.checkServerIdentity
function that implements the desired behavior.
The host name or IP address to verify the certificate against.
+A certificate object
representing the peer's certificate.
Optional
ciphersCipher suite specification, replacing the default. For more +information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
+The time in milliseconds to attempt a connection before timing out.
+Optional
credentialsOptional
crlPEM formatted CRLs (Certificate Revocation Lists).
+Allow a driver to force a Single topology type with a connection string containing one host
+Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
+Optional
ecdhA string describing a named curve or a colon separated list of curve +NIDs or names, for example P-521:P-384:P-256, to use for ECDH key +agreement. Set to auto to select the curve automatically. Use +crypto.getCurves() to obtain a list of available curve names. On +recent releases, openssl ecparam -list_curves will also display the +name and description of each available elliptic curve. Default: +tls.DEFAULT_ECDH_CURVE.
+Optional
familyForce server to assign _id
values instead of driver
heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one.
+Optional
hintsOptional
keyPrivate keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase:
Optional
localOptional
localThe size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances.
+Optional
lookupThe maximum number of connections that may be in the process of being established concurrently by the connection pool.
+The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed.
+The maximum number of connections in the connection pool.
+Optional
minDHSizeSets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort.
+The minimum number of connections in the connection pool.
+Enable command monitoring for this client
+TCP Connection no delay
+Optional
passphraseShared passphrase used for a single private key and/or a PFX.
+Optional
pfxPFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase:
A primary key factory function for generation of custom _id
keys
Optional
proxyOptional
proxyOptional
proxyOptional
proxyEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
rejectIf true the server will reject any connection which is not +authorized with the list of supplied CAs. This option only has an +effect if requestCert is true.
+Specifies the name of the replica set, if the mongod is a member of a replica set.
+Enables retryable reads.
+Enable retryable writes.
+Optional
secureAn optional TLS context object from tls.createSecureContext()
+Optional
secureLegacy mechanism to select the TLS protocol version to use, it does +not support independent control of the minimum and maximum version, +and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow +any TLS protocol version up to TLSv1.3. It is not recommended to use +TLS versions less than 1.2, but it may be required for +interoperability. Default: none, see minVersion.
+Optional
servernameSpecifies how long (in milliseconds) to block for server selection before throwing an exception.
+Optional
sessionAn optional Buffer instance containing a TLS session.
+The time in milliseconds to attempt a send or receive on a socket before the attempt times out.
+Optional
srvThe maximum number of hosts to connect to when using an srv connection string, a setting of 0
means unlimited hosts
Modifies the srv URI to look like:
+_{srvServiceName}._tcp.{hostname}.{domainname}
Querying this DNS URI is expected to respond with SRV records
+If tls
is provided as an option, it is equivalent to setting the ssl
option.
NodeJS native TLS options are passed through to the socket and retain their original types.
+nodejs native option | +driver spec equivalent option name | +driver option type | +
---|---|---|
ca |
+tlsCAFile |
+string |
+
crl |
+tlsCRLFile |
+string |
+
cert |
+tlsCertificateKeyFile |
+string |
+
key |
+tlsCertificateKeyFile |
+string |
+
passphrase |
+tlsCertificateKeyFilePassword |
+string |
+
rejectUnauthorized |
+tlsAllowInvalidCertificates |
+boolean |
+
checkServerIdentity |
+tlsAllowInvalidHostnames |
+boolean |
+
see note below | +tlsInsecure |
+boolean |
+
If tlsInsecure
is set to true
, then it will set the node native options checkServerIdentity
+to a no-op and rejectUnauthorized
to false
.
If tlsInsecure
is set to false
, then it will set the node native options checkServerIdentity
+to a no-op and rejectUnauthorized
to the inverse value of tlsAllowInvalidCertificates
. If
+tlsAllowInvalidCertificates
is not set, then rejectUnauthorized
will be set to true
.
tlsCAFile
, tlsCertificateKeyFile
and tlsCRLFile
The files specified by the paths passed in to the tlsCAFile
, tlsCertificateKeyFile
and tlsCRLFile
+fields are read lazily on the first call to MongoClient.connect
. Once these files have been read and
+the ca
, cert
, crl
and key
fields are populated, they will not be read again on subsequent calls to
+MongoClient.connect
. As a result, until the first call to MongoClient.connect
, the ca
,
+cert
, crl
and key
fields will be undefined.
Bypasses validation of the certificates presented by the mongod/mongos instance
+Disables hostname validation of the certificate presented by the mongod/mongos instance.
+Optional
tlsCAFileOptional
tlsOptional
tlsCRLFileDisables various certificate validations.
+The maximum time in milliseconds that a thread can wait for a connection to become available.
+An integer that specifies the compression level if using zlib for network compression.
+Optional
allowOptional
ALPNProtocolsAn array of strings or a Buffer naming possible ALPN protocols. +(Protocols should be ordered by their priority.)
+Optional
autoOptional
autoOptional
caOptionally override the trusted CA certificates. Default is to trust +the well-known CAs curated by Mozilla. Mozilla's CAs are completely +replaced when CAs are explicitly specified using this option.
+Optional
cancellationOptional
certCert chains in PEM format. One cert chain should be provided per +private key. Each cert chain should consist of the PEM formatted +certificate for a provided private key, followed by the PEM +formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, +see ca). When providing multiple cert chains, they do not have to +be in the same order as their private keys in key. If the +intermediate certificates are not provided, the peer will not be +able to validate the certificate, and the handshake will fail.
+Optional
checkVerifies the certificate cert
is issued to hostname
.
Returns Error object, populating it with reason
, host
, and cert
on
+failure. On success, returns undefined.
This function is intended to be used in combination with thecheckServerIdentity
option that can be passed to connect and as
+such operates on a certificate object
. For other purposes, consider using x509.checkHost()
instead.
This function can be overwritten by providing an alternative function as the options.checkServerIdentity
option that is passed to tls.connect()
. The
+overwriting function can call tls.checkServerIdentity()
of course, to augment
+the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as
+being issued by trusted CA (options.ca
).
Earlier versions of Node.js incorrectly accepted certificates for a givenhostname
if a matching uniformResourceIdentifier
subject alternative name
+was present (see CVE-2021-44531). Applications that wish to acceptuniformResourceIdentifier
subject alternative names can use
+a custom options.checkServerIdentity
function that implements the desired behavior.
The host name or IP address to verify the certificate against.
+A certificate object
representing the peer's certificate.
Optional
ciphersCipher suite specification, replacing the default. For more +information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
+Optional
compressorsOptional
credentialsOptional
crlPEM formatted CRLs (Certificate Revocation Lists).
+Optional
ecdhA string describing a named curve or a colon separated list of curve +NIDs or names, for example P-521:P-384:P-256, to use for ECDH key +agreement. Set to auto to select the curve automatically. Use +crypto.getCurves() to obtain a list of available curve names. On +recent releases, openssl ecparam -list_curves will also display the +name and description of each available elliptic curve. Default: +tls.DEFAULT_ECDH_CURVE.
+Optional
familyOptional
hintsOptional
keyPrivate keys in PEM format. PEM allows the option of private keys
+being encrypted. Encrypted keys will be decrypted with
+options.passphrase. Multiple keys using different algorithms can be
+provided either as an array of unencrypted key strings or buffers,
+or an array of objects in the form {pem: <string|buffer>[,
+passphrase:
Optional
localOptional
localOptional
logicalOptional
lookupOptional
minDHSizeOptional
noOptional
passphraseShared passphrase used for a single private key and/or a PFX.
+Optional
pfxPFX or PKCS12 encoded private key and certificate chain. pfx is an
+alternative to providing key and cert individually. PFX is usually
+encrypted, if it is, passphrase will be used to decrypt it. Multiple
+PFX can be provided either as an array of unencrypted PFX buffers,
+or an array of objects in the form {buf: <string|buffer>[,
+passphrase:
Optional
proxyOptional
proxyOptional
proxyOptional
proxyOptional
rejectIf true the server will reject any connection which is not +authorized with the list of supplied CAs. This option only has an +effect if requestCert is true.
+Optional
secureAn optional TLS context object from tls.createSecureContext()
+Optional
secureLegacy mechanism to select the TLS protocol version to use, it does +not support independent control of the minimum and maximum version, +and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow +any TLS protocol version up to TLSv1.3. It is not recommended to use +TLS versions less than 1.2, but it may be required for +interoperability. Default: none, see minVersion.
+Optional
serverOptional
servernameOptional
sessionAn optional Buffer instance containing a TLS session.
+Optional
socketThe parameters that the driver provides to the user supplied +human or machine callback.
+The version number is used to communicate callback API changes that are not breaking but that +users may want to know about and review their implementation. Users may wish to check the version +number and throw an error if their expected version number and the one provided do not match.
+Optional
idpThe IdP information returned from the server.
+Optional
refreshThe refresh token, if applicable, to be used by the callback to request a new token from the issuer.
+The context in which to timeout the OIDC callback.
+Optional
usernameOptional username.
+The current OIDC API version.
+The response required to be returned from the machine or +human callback workflows' callback.
+The OIDC access token.
+Optional
expiresThe time when the access token expires. For future use.
+Optional
refreshThe refresh token, if applicable, to be used by the callback to request a new token from the issuer.
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willRangeOptions specifies index options for a Queryable Encryption field supporting "range" queries. +min, max, sparsity, trimFactor and range must match the values set in the encryptedFields of the destination collection. +For double and decimal128, min/max/precision must all be set, or all be unset.
+Optional
maxmax is the minimum value for the encrypted index. Required if precision is set.
+Optional
minmin is the minimum value for the encrypted index. Required if precision is set.
+Optional
precisionOptional
sparsitysparsity may be used to tune performance. must be non-negative. When omitted, a default value is used.
+Optional
trimtrimFactor may be used to tune performance. must be non-negative. When omitted, a default value is used.
+Optional
hedgeServer mode in which the same query is dispatched in parallel to multiple replica set members.
+Optional
maxMax secondary read staleness in seconds, Minimum value is 90 seconds.
+Optional
readOptional
readOptional
sessionOptional
hedgeServer mode in which the same query is dispatched in parallel to multiple replica set members.
+Optional
maxMax secondary read staleness in seconds, Minimum value is 90 seconds.
+Optional
readOptional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
dropDrop the target name collection if it previously exists.
+Optional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
new_Unclear
+Optional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Optional
collationSpecifies a collation.
+The filter to limit the replaced document.
+Optional
hintThe index to use. If specified, then the query system will only consider plans using the hinted index.
+The document with which to replace the matched document.
+Optional
upsertWhen true, creates a new document if no document matches the query.
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassIf true, allows the write to opt-out of document level validation
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecifies a collation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintSpecify that the update query should only consider plans using the hinted index
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
upsertWhen true, creates a new document if no document matches the query
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+Configuration options for timeseries collections
+Configuration options for a transaction.
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxSpecifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds
+Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readA default read concern for commands in this transaction
+Optional
readA default read preference for commands in this transaction
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeA default writeConcern for commands in this transaction
+Optional
disambiguatedA document containing additional information about any ambiguous update paths from the update event. The document
+maps the full ambiguous update path to an array containing the actual resolved components of the path. For example,
+given a document shaped like { a: { '0': 0 } }
, and an update of { $inc: 'a.0' }
, disambiguated paths would look like
+the following:
{
'a.0': ['a', '0']
}
+
+
+This field is only present when there are ambiguous paths that are updated as a part of the update event and showExpandedEvents
+is enabled for the change stream.
Optional
removedAn array of field names that were removed from the document.
+Optional
truncatedAn array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages:
+The name of the truncated field.
+The number of elements in the truncated array.
+Optional
updatedA document containing key:value pairs of names of the fields that were +changed, and the new value for those fields.
+Optional
arrayA set of filters specifying to which array elements an update should apply.
+Optional
collationSpecifies a collation.
+The filter to limit the updated documents.
+Optional
hintThe index to use. If specified, then the query system will only consider plans using the hinted index.
+The modifications to apply. The value can be either:
+UpdateFilter
Optional
upsertWhen true, creates a new document if no document matches the query.
+Optional
arrayA set of filters specifying to which array elements an update should apply.
+Optional
collationSpecifies a collation.
+The filter to limit the updated documents.
+Optional
hintThe index to use. If specified, then the query system will only consider plans using the hinted index.
+The modifications to apply. The value can be either:
+UpdateFilter
Optional
upsertWhen true, creates a new document if no document matches the query.
+Optional
arrayA set of filters specifying to which array elements an update should apply
+Optional
authdbOptional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
bypassIf true, allows the write to opt-out of document level validation
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationSpecifies a collation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
hintSpecify that the update query should only consider plans using the hinted index
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
letMap of parameter names and values that can be accessed using $$var (requires MongoDB 5.0).
+Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
upsertWhen true, creates a new document if no document matches the query
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+TSchema
is the schema of the collection
Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined
+The number of documents that matched the filter
+The number of documents that were modified
+The number of documents that were upserted
+The identifier of the inserted document if an upsert took place
+Optional
arrayAn array of filter documents that determines which array elements to modify for an update operation on an array field.
+Optional
collationSpecifies the collation to use for the operation.
+Optional
hintA document or string that specifies the index to use to support the query predicate.
+Optional
multiIf true, updates all documents that meet the query criteria.
+The query that matches documents to update.
+The modifications to apply.
+Optional
upsertIf true, perform an insert if no documents match the query.
+Optional
authdbOptional
backgroundValidates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+)
+Optional
bsonreturn BSON regular expressions as BSONRegExp instances.
+Optional
checkthe serializer will check if keys are valid.
+Optional
collationCollation
+Optional
commentComment to apply to the operation.
+In server versions pre-4.4, 'comment' must be string. A server +error will be thrown if any other type is provided.
+In server versions 4.4 and above, 'comment' can be any valid BSON type.
+Optional
dbOptional
enableEnable utf8 validation when deserializing BSON documents. Defaults to true.
+Optional
explainSpecifies the verbosity mode for the explain output.
+Optional
fieldsallow to specify if there what fields we wish to return as unserialized raw buffer.
+Optional
ignoreserialize will not emit undefined fields
+note that the driver sets this to false
Optional
maxOptional
noOptional
omitOptional
promotewhen deserializing a Binary will return it as a node.js Buffer instance.
+Optional
promotewhen deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+Optional
promotewhen deserializing will promote BSON values to their Node.js closest equivalent types.
+Optional
rawEnabling the raw option will return a Node.js Buffer +which is allocated using allocUnsafe API. +See this section from the Node.js Docs here +for more detail about what "unsafe" refers to in this context. +If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate +your own buffer and clone the contents:
+const raw = await collection.findOne({}, { raw: true });
const myBuffer = Buffer.alloc(raw.byteLength);
myBuffer.set(raw, 0);
// Only save and use `myBuffer` beyond this point
+
+
+Please note there is a known limitation where this option cannot be used at the MongoClient level (see NODE-3946).
+It does correctly work at Db
, Collection
, and per operation the same as other BSON options work.
Optional
readSpecify a read concern and level for the collection. (only MongoDB 3.2 or higher supported)
+Optional
readThe preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).
+Optional
retryShould retry failed writes
+Optional
serializeserialize the javascript functions
+Optional
sessionSpecify ClientSession for this command
+Optional
usewhen deserializing a Long return as a BigInt.
+Optional
willOptional
writeWrite Concern as an object
+The type of the result property of MongoWriteConcernError
+Optional
fsyncThe file sync write concern.
+Optional
jThe journal write concern.
+Optional
journalThe journal write concern
+Optional
wThe write concern
+Optional
wtimeoutThe write concern timeout.
+Optional
wtimeoutMSThe write concern timeout
+It is possible to search using alternative types in mongodb e.g. +string types can be searched using a regex in mongo +array types can be searched using their element type
+Extra options related to the mongocryptd process +* Available in MongoDB 6.0 or higher.
+The level of severity of the log message
+Value | +Level | +
---|---|
0 | +Fatal Error | +
1 | +Error | +
2 | +Warning | +
3 | +Info | +
4 | +Trace | +
The client ID to authenticate a registered application
+The client secret to authenticate a registered application
+Optional
identityIf present, a host with optional port. E.g. "example.com" or "example.com:443". +This is optional, and only needed if customer is using a non-commercial Azure instance +(e.g. a government or China account, which use different URLs). +Defaults to "login.microsoftonline.com"
+The tenant ID identifies the organization for the account
+If present, an access token to authenticate with Azure.
+Optional
legacy?: booleanOutput using the Extended JSON v1 spec
+Optional
relaxed?: booleanEnable Extended JSON's relaxed
mode, which attempts to return native JS types where possible, rather than BSON types
Optional
useEnable native bigint support
+Experimental
A new set of BSON APIs that are currently experimental and not intended for production use.
+A data key provider. Allowed values:
+mongodb-client-encryption>=6.0.1
only) a named key, in the form of:
+aws:<name>
, gcp:<name>
, local:<name>
, kmip:<name>
, azure:<name>
+where name
is an alphanumeric string, underscores allowed.Socket options to use for KMS requests.
+TLS options to use when connecting. The spec specifically calls out which insecure +tls options are not allowed:
+These options are not included in the type, and are ignored if provided.
+TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions
+Event description type
+For backwards compatibility, true is interpreted as "allPlansExecution" +and false as "queryPlanner". Prior to server version 3.6, aggregate() +ignores the verbosity parameter and executes in "queryPlanner".
+The service account email to authenticate
+Optional
endpoint?: stringIf present, a host with optional port. E.g. "example.com" or "example.com:443". +Defaults to "oauth2.googleapis.com"
+A PKCS#8 encrypted key. This can either be a base64 string or a binary representation
+If present, an access token to authenticate with GCP.
+The index information returned by the listIndexes command. https://www.mongodb.com/docs/manual/reference/command/listIndexes/#mongodb-dbcommand-dbcmd.listIndexes
+Given an object shaped type, return the type of the _id field or default to ObjectId
+returns tuple of strings (keys to be joined on '.') that represent every path into a schema +https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
+Through testing we determined that a depth of 8 is safe for the typescript compiler +and provides reasonable compilation times. This number is otherwise not special and +should be changed if issues are found with this level of checking. Beyond this +depth any helpers that make use of NestedPaths should devolve to not asserting any +type safety on the input.
+returns keys (strings) for every path into a schema with a value of type +https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
+A type that extends Document but forbids anything that "looks like" an object id.
+It avoids using fields with not acceptable types
+The signature of the human or machine callback functions.
+Represents a specific point in time on a server. Can be retrieved by using db.command()
Add an optional _id field to an object shaped type
+Adds an optional _id field to an object shaped type, unless the _id field is required on that type. +In the case _id is required, this method continues to require_id.
+Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server.
+Optional
readThe read preference
+Optional
session?: ClientSessionSpecify ClientSession for this command
+Experimental
Experimental
Experimental
Add an _id field to an object shaped type
+Const
Const
Const
Const
Const
Const
Experimental
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
Const
An enumeration of server types we know about
+Const
An enumeration of topology types we know about
+
An alias for AbstractCursor.close|AbstractCursor.close().
+