Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Events and Timers

Node.js events.getEventListeners() function

Reference for events.getEventListeners() in Node.js: read the listeners of an EventEmitter or EventTarget, for example an AbortSignal, with examples.

events.getEventListeners(emitterOrTarget, eventName) returns a copy of the functions registered for an event. It works on an EventEmitter and, more importantly, on an EventTarget, which has no method for listing its own listeners.

It is a diagnostics tool: use it in tests and debugging to check that listeners were added and removed as expected, for instance on an AbortSignal that seems to leak.

NODE
import { getEventListeners } from 'node:events';
console.log(getEventListeners(signal, 'abort').length);

Try it

Node.js Emitters and event targets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Finding a listener leak on an AbortSignal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
import { getEventListeners } from 'node:events';

getEventListeners(emitterOrTarget: EventEmitter | EventTarget, eventName: string | symbol): Function[]
Name Description
emitterOrTarget The object to inspect.
eventName The event whose listeners to return.

Returns: a new array of listener functions. For an EventTarget, listeners registered as objects with handleEvent are returned as the registered values.

Errors: ERR_INVALID_ARG_TYPE if the first argument is neither an emitter nor an event target.

Usage notes

  • Copy. Changing the returned array does not affect the target.
  • Emitters. For an EventEmitter the result matches emitter.listeners(eventName). The helper exists mostly so the same call also works on event targets.
  • No once unwrapping needed for targets. EventTarget has its own { once: true } flag, and the registered function is returned as you passed it.
  • EventTarget ignores duplicates. Adding the same function with the same options twice registers it once, unlike EventEmitter.
  • Useful with AbortSignal. Counting 'abort' listeners helps verify cleanup code. The same signal is often shared by many operations, which can produce a MaxListenersExceededWarning.
  • Diagnostics only. Do not build program logic on listener counts of objects you do not own.
  • Companion helper. events.getMaxListeners() reports the current warning limit for the same kinds of objects. See setMaxListeners().
  • Added in Node.js 15.2 (also back-ported to 14.17).