home / documentation / v19 / events

Events

目录

Added in: v0.10.0

稳定性: 2 - Stable

Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called.

For instance: a net.Server object emits an event each time a peer connects to it; a fs.ReadStream emits an event when the file is opened; a stream emits an event whenever data is available to be read.

All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and discarded.

The following example shows a simple EventEmitter instance with a single listener. The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.

MJS
CJS

Passing arguments and this to listeners

The eventEmitter.emit() method allows an arbitrary set of arguments to be passed to the listener functions. Keep in mind that when an ordinary listener function is called, the standard this keyword is intentionally set to reference the EventEmitter instance to which the listener is attached.

JS

It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the this keyword will no longer reference the EventEmitter instance:

JS

Asynchronous vs. synchronous

The EventEmitter calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the setImmediate() or process.nextTick() methods:

JS

Handling events only once

When a listener is registered using the eventEmitter.on() method, that listener is invoked every time the named event is emitted.

JS

Using the eventEmitter.once() method, it is possible to register a listener that is called at most once for a particular event. Once the event is emitted, the listener is unregistered and then called.

JS

Error events

When an error occurs within an EventEmitter instance, the typical action is for an 'error' event to be emitted. These are treated as special cases within Node.js.

If an EventEmitter does not have at least one listener registered for the 'error' event, and an 'error' event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.

JS

To guard against crashing the Node.js process the domain module can be used. (Note, however, that the node:domain module is deprecated.)

As a best practice, listeners should always be added for the 'error' events.

JS

It is possible to monitor 'error' events without consuming the emitted error by installing a listener using the symbol events.errorMonitor.

MJS
CJS

Capture rejections of promises

Using async functions with event handlers is problematic, because it can lead to an unhandled rejection in case of a thrown exception:

JS

The captureRejections option in the EventEmitter constructor or the global setting change this behavior, installing a .then(undefined, handler) handler on the Promise. This handler routes the exception asynchronously to the Symbol.for('nodejs.rejection') method if there is one, or to 'error' event handler if there is none.

JS

Setting events.captureRejections = true will change the default for all new instances of EventEmitter.

MJS
CJS

The 'error' events that are generated by the captureRejections behavior do not have a catch handler to avoid infinite error loops: the recommendation is to not use async functions as 'error' event handlers.

C EventEmitter

历史
版本更改
v13.4.0, v12.16.0Added captureRejections option.
v0.1.26Added in: v0.1.26

The EventEmitter class is defined and exposed by the node:events module:

MJS
CJS

All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when existing listeners are removed.

It supports the following option:

E 'newListener'

Added in: v0.1.26

  • eventName string | symbol The name of the event being listened for
  • listener Function The event handler function

The EventEmitter instance will emit its own 'newListener' event before a listener is added to its internal array of listeners.

Listeners registered for the 'newListener' event are passed the event name and a reference to the listener being added.

The fact that the event is triggered before adding the listener has a subtle but important side effect: any additional listeners registered to the same name within the 'newListener' callback are inserted before the listener that is in the process of being added.

JS

E 'removeListener'

历史
版本更改
v6.1.0, v4.7.0For listeners attached using `.once()`, the `listener` argument now yields the original listener function.
v0.9.3Added in: v0.9.3

The 'removeListener' event is emitted after the listener is removed.

M emitter.addListener(eventName, listener)

Added in: v0.1.26

Alias for emitter.on(eventName, listener).

M emitter.emit(eventName[, ...args])

Added in: v0.1.26

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.

MJS
CJS

M emitter.eventNames()

Added in: v6.0.0

Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

MJS
CJS

M emitter.getMaxListeners()

Added in: v1.0.0

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.

M emitter.listenerCount(eventName)

Added in: v3.2.0

Returns the number of listeners listening to the event named eventName.

M emitter.listeners(eventName)

历史
版本更改
v7.0.0For listeners attached using `.once()` this returns the original listeners instead of wrapper functions now.
v0.1.26Added in: v0.1.26

Returns a copy of the array of listeners for the event named eventName.

JS

M emitter.off(eventName, listener)

Added in: v10.0.0

Alias for emitter.removeListener().

M emitter.on(eventName, listener)

Added in: v0.1.101

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.

JS

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.

JS

M emitter.once(eventName, listener)

Added in: v0.3.0

Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

JS

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.

JS

M emitter.prependListener(eventName, listener)

Added in: v6.0.0

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.

JS

Returns a reference to the EventEmitter, so that calls can be chained.

M emitter.prependOnceListener(eventName, listener)

Added in: v6.0.0

Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

JS

Returns a reference to the EventEmitter, so that calls can be chained.

M emitter.removeAllListeners([eventName])

Added in: v0.1.26

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.

M emitter.removeListener(eventName, listener)

Added in: v0.1.26

Removes the specified listener from the listener array for the event named eventName.

JS

removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.

JS

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:

JS

Returns a reference to the EventEmitter, so that calls can be chained.

M emitter.setMaxListeners(n)

Added in: v0.3.5

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

Returns a reference to the EventEmitter, so that calls can be chained.

M emitter.rawListeners(eventName)

Added in: v9.4.0

Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

JS

M emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])

历史
版本更改
v17.4.0, v16.14.0No longer experimental.
v13.4.0, v12.16.0Added in: v13.4.0, v12.16.0

The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').

MJS
CJS

M events.defaultMaxListeners

Added in: v0.11.2

By 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 all EventEmitter 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:

JS

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'.

M events.errorMonitor

Added in: v13.6.0, v12.17.0

This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an 'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.

M events.getEventListeners(emitterOrTarget, eventName)

Added in: v15.2.0, v14.17.0

Returns a copy of the array of listeners for the event named eventName.

For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

MJS
CJS

M events.once(emitter, name[, options])

历史
版本更改
v15.0.0The `signal` option is supported now.
v11.13.0, v10.16.0Added in: v11.13.0, v10.16.0

Creates 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.

MJS
CJS

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:

MJS
CJS

An AbortSignal can be used to cancel waiting for the event:

MJS
CJS

Awaiting multiple events emitted on process.nextTick()

There is an edge case worth noting when using the events.once() function to await multiple events emitted on in the same batch of process.nextTick() operations, or whenever multiple events are emitted synchronously. Specifically, because the process.nextTick() queue is drained before the Promise microtask queue, and because EventEmitter emits all events synchronously, it is possible for events.once() to miss an event.

MJS
CJS

To catch both events, create each of the Promises before awaiting either of them, then it becomes possible to use Promise.all(), Promise.race(), or Promise.allSettled():

MJS
CJS

M events.captureRejections

历史
版本更改
v17.4.0, v16.14.0No longer experimental.
v13.4.0, v12.16.0Added in: v13.4.0, v12.16.0

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

M events.captureRejectionSymbol

历史
版本更改
v17.4.0, v16.14.0No longer experimental.
v13.4.0, v12.16.0Added in: v13.4.0, v12.16.0

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

M events.listenerCount(emitter, eventName)

Deprecated in: v3.2.0

稳定性: 0 - Deprecated: Use `emitter.listenerCount()` instead.

A class method that returns the number of listeners for the given eventName registered on the given emitter.

MJS
CJS

M events.on(emitter, eventName[, options])

Added in: v13.6.0, v12.16.0

MJS
CJS

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:

MJS
CJS

M events.setMaxListeners(n[, ...eventTargets])

Added in: v15.4.0

  • n number A non-negative number. The maximum number of listeners per EventTarget event.
  • ...eventsTargets EventTarget[]|EventEmitter[] Zero or more EventTarget or EventEmitter instances. If none are specified, n is set as the default max for all newly created EventTarget and EventEmitter objects.
MJS
CJS

C events.EventEmitterAsyncResource extends EventEmitter

Added in: v17.4.0, v16.14.0

Integrates EventEmitter with AsyncResource for EventEmitters that require manual async tracking. Specifically, all events emitted by instances of events.EventEmitterAsyncResource will run within its async context.

MJS
CJS

The EventEmitterAsyncResource class has the same methods and takes the same options as EventEmitter and AsyncResource themselves.

M new events.EventEmitterAsyncResource(options)

  • options Object
    • captureRejections boolean It enables automatic capturing of promise rejection. Default: false.
    • name string The type of async event. Default::new.target.name.
    • triggerAsyncId number The ID of the execution context that created this async event. Default: executionAsyncId().
    • requireManualDestroy boolean If set to true, disables emitDestroy when the object is garbage collected. This usually does not need to be set (even if emitDestroy is called manually), unless the resource's asyncId is retrieved and the sensitive API's emitDestroy is called with it. When set to false, the emitDestroy call on garbage collection will only take place if there is at least one active destroy hook. Default: false.

M eventemitterasyncresource.asyncId

  • Type: number The unique asyncId assigned to the resource.

M eventemitterasyncresource.asyncResource

The returned AsyncResource object has an additional eventEmitter property that provides a reference to this EventEmitterAsyncResource.

M eventemitterasyncresource.emitDestroy()

Call all destroy hooks. This should only ever be called once. An error will be thrown if it is called more than once. This must be manually called. If the resource is left to be collected by the GC then the destroy hooks will never be called.

M eventemitterasyncresource.triggerAsyncId

  • Type: number The same triggerAsyncId that is passed to the AsyncResource constructor.

M EventTarget and Event API

历史
版本更改
v16.0.0changed EventTarget error handling.
v15.4.0No longer experimental.
v15.0.0The `EventTarget` and `Event` classes are now available as globals.
v14.5.0Added in: v14.5.0

The EventTarget and Event objects are a Node.js-specific implementation of the EventTarget Web API that are exposed by some Node.js core APIs.

JS

Node.js EventTarget vs. DOM EventTarget

There are two key differences between the Node.js EventTarget and the EventTarget Web API:

  1. Whereas DOM EventTarget instances may be hierarchical, there is no concept of hierarchy and event propagation in Node.js. That is, an event dispatched to an EventTarget does not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event.
  2. In the Node.js EventTarget, if an event listener is an async function or returns a Promise, and the returned Promise rejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (see EventTarget error handling for details).

M NodeEventTarget vs. EventEmitter

The NodeEventTarget object implements a modified subset of the EventEmitter API that allows it to closely emulate an EventEmitter in certain situations. A NodeEventTarget is not an instance of EventEmitter and cannot be used in place of an EventEmitter in most cases.

  1. Unlike EventEmitter, any given listener can be registered at most once per event type. Attempts to register a listener multiple times are ignored.
  2. The NodeEventTarget does not emulate the full EventEmitter API. Specifically the prependListener(), prependOnceListener(), rawListeners(), setMaxListeners(), getMaxListeners(), and errorMonitor APIs are not emulated. The 'newListener' and 'removeListener' events will also not be emitted.
  3. The NodeEventTarget does not implement any special default behavior for events with type 'error'.
  4. The NodeEventTarget supports EventListener objects as well as functions as handlers for all event types.

Event listener

Event listeners registered for an event type may either be JavaScript functions or objects with a handleEvent property whose value is a function.

In either case, the handler function is invoked with the event argument passed to the eventTarget.dispatchEvent() function.

Async functions may be used as event listeners. If an async handler function rejects, the rejection is captured and handled as described in EventTarget error handling.

An error thrown by one handler function does not prevent the other handlers from being invoked.

The return value of a handler function is ignored.

Handlers are always invoked in the order they were added.

Handler functions may mutate the event object.

JS

M EventTarget error handling

When a registered event listener throws (or returns a Promise that rejects), by default the error is treated as an uncaught exception on process.nextTick(). This means uncaught exceptions in EventTargets will terminate the Node.js process by default.

Throwing within an event listener will not stop the other registered handlers from being invoked.

The EventTarget does not implement any special default handling for 'error' type events like EventEmitter.

Currently errors are first forwarded to the process.on('error') event before reaching process.on('uncaughtException'). This behavior is deprecated and will change in a future release to align EventTarget with other Node.js APIs. Any code relying on the process.on('error') event should be aligned with the new behavior.

C Event

历史
版本更改
v15.0.0The `Event` class is now available through the global object.
v14.5.0Added in: v14.5.0

The Event object is an adaptation of the Event Web API. Instances are created internally by Node.js.

M event.bubbles

Added in: v14.5.0

  • Type: boolean Always returns false.

This is not used in Node.js and is provided purely for completeness.

M event.cancelBubble()

Added in: v14.5.0

Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness.

M event.cancelable

Added in: v14.5.0

  • Type: boolean True if the event was created with the cancelable option.
M event.composed

Added in: v14.5.0

  • Type: boolean Always returns false.

This is not used in Node.js and is provided purely for completeness.

M event.composedPath()

Added in: v14.5.0

Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness.

M event.currentTarget

Added in: v14.5.0

  • Type: EventTarget The EventTarget dispatching the event.

Alias for event.target.

M event.defaultPrevented

Added in: v14.5.0

Is true if cancelable is true and event.preventDefault() has been called.

M event.eventPhase

Added in: v14.5.0

  • Type: number Returns 0 while an event is not being dispatched, 2 while it is being dispatched.

This is not used in Node.js and is provided purely for completeness.

M event.isTrusted

Added in: v14.5.0

The AbortSignal "abort" event is emitted with isTrusted set to true. The value is false in all other cases.

M event.preventDefault()

Added in: v14.5.0

Sets the defaultPrevented property to true if cancelable is true.

M event.returnValue

Added in: v14.5.0

  • Type: boolean True if the event has not been canceled.

This is not used in Node.js and is provided purely for completeness.

M event.srcElement

Added in: v14.5.0

  • Type: EventTarget The EventTarget dispatching the event.

Alias for event.target.

M event.stopImmediatePropagation()

Added in: v14.5.0

Stops the invocation of event listeners after the current one completes.

M event.stopPropagation()

Added in: v14.5.0

This is not used in Node.js and is provided purely for completeness.

M event.target

Added in: v14.5.0

  • Type: EventTarget The EventTarget dispatching the event.
M event.timeStamp

Added in: v14.5.0

The millisecond timestamp when the Event object was created.

M event.type

Added in: v14.5.0

The event type identifier.

C EventTarget

历史
版本更改
v15.0.0The `EventTarget` class is now available through the global object.
v14.5.0Added in: v14.5.0
M eventTarget.addEventListener(type, listener[, options])
历史
版本更改
v15.4.0add support for `signal` option.
v14.5.0Added in: v14.5.0
  • type string
  • listener Function | EventListener
  • options Object
    • once boolean When true, the listener is automatically removed when it is first invoked. Default: false.
    • passive boolean When true, serves as a hint that the listener will not call the Event object's preventDefault() method. Default: false.
    • capture boolean Not directly used by Node.js. Added for API completeness. Default: false.
    • signal AbortSignal The listener will be removed when the given AbortSignal object's abort() method is called.

Adds a new handler for the type event. Any given listener is added only once per type and per capture option value.

If the once option is true, the listener is removed after the next time a type event is dispatched.

The capture option is not used by Node.js in any functional way other than tracking registered event listeners per the EventTarget specification. Specifically, the capture option is used as part of the key when registering a listener. Any individual listener may be added once with capture = false, and once with capture = true.

JS
M eventTarget.dispatchEvent(event)

Added in: v14.5.0

  • event Event
  • Returns: boolean true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, otherwise false.

Dispatches the event to the list of handlers for event.type.

The registered event listeners is synchronously invoked in the order they were registered.

M eventTarget.removeEventListener(type, listener)

Added in: v14.5.0

Removes the listener from the list of handlers for event type.

C CustomEvent

Added in: v18.7.0, v16.17.0

稳定性: 1 - Experimental.

The CustomEvent object is an adaptation of the CustomEvent Web API. Instances are created internally by Node.js.

M event.detail

Added in: v18.7.0, v16.17.0

稳定性: 1 - Experimental.
  • Type: any Returns custom data passed when initializing.

Read-only.

C NodeEventTarget

Added in: v14.5.0

The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API.

M nodeEventTarget.addListener(type, listener[, options])

Added in: v14.5.0

Node.js-specific extension to the EventTarget class that emulates the equivalent EventEmitter API. The only difference between addListener() and addEventListener() is that addListener() will return a reference to the EventTarget.

M nodeEventTarget.eventNames()

Added in: v14.5.0

  • Returns: string[]

Node.js-specific extension to the EventTarget class that returns an array of event type names for which event listeners are registered.

M nodeEventTarget.listenerCount(type)

Added in: v14.5.0

Node.js-specific extension to the EventTarget class that returns the number of event listeners registered for the type.

M nodeEventTarget.off(type, listener)

Added in: v14.5.0

Node.js-specific alias for eventTarget.removeListener().

M nodeEventTarget.on(type, listener[, options])

Added in: v14.5.0

Node.js-specific alias for eventTarget.addListener().

M nodeEventTarget.once(type, listener[, options])

Added in: v14.5.0

Node.js-specific extension to the EventTarget class that adds a once listener for the given event type. This is equivalent to calling on with the once option set to true.

M nodeEventTarget.removeAllListeners([type])

Added in: v14.5.0

Node.js-specific extension to the EventTarget class. If type is specified, removes all registered listeners for type, otherwise removes all registered listeners.

M nodeEventTarget.removeListener(type, listener)

Added in: v14.5.0

Node.js-specific extension to the EventTarget class that removes the listener for the given type. The only difference between removeListener() and removeEventListener() is that removeListener() will return a reference to the EventTarget.