Node.js Reference ยท Events and Timers
Node.js emitter.listeners() and listenerCount()
Reference for emitter.listeners(), rawListeners(), listenerCount() and eventNames() in Node.js: inspecting what is registered, copies and once wrappers.
These methods let you look at what is registered on an emitter without triggering anything. listeners(name) returns the listener functions, rawListeners(name) returns them including the wrappers that once() creates, listenerCount(name) returns how many there are, and eventNames() returns every event name that currently has at least one listener.
They are mostly used in tests, in diagnostics for leaking listeners, and in libraries that behave differently when nobody is listening.
console.log(emitter.listenerCount('data'));
Try it
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.
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
emitter.listeners(eventName: string | symbol): Function[] emitter.rawListeners(eventName: string | symbol): Function[] emitter.listenerCount(eventName: string | symbol, listener?: Function): number emitter.eventNames(): (string | symbol)[]
| Name | Description |
|---|---|
eventName |
The event to inspect. |
listener |
Optional. When given, listenerCount() counts only registrations of that function. |
Returns: a new array of functions (listeners, rawListeners), a number (listenerCount), or an array of strings and symbols (eventNames). An event with no listeners gives an empty array or 0.
Usage notes
- Copies. The arrays are copies. Modifying them does not change the emitter; use
off()for that. - Order. Items appear in the order they will be called.
oncewrappers.listeners()unwrapsonce()registrations to the original function,rawListeners()does not. UserawListeners()when you want to call a listener manually without it staying registered twice.- Counting a specific function. The second argument to
listenerCount()counts how many times that function is registered, includingonce()registrations. eventNames()order. It lists strings first in insertion order, then symbols, which is the order ofReflect.ownKeys().- Empty events disappear. After the last listener of an event is removed, the name no longer shows in
eventNames(). - Deprecated static.
EventEmitter.listenerCount(emitter, name)still works but is deprecated; use the instance method. - For
EventTargetobjects these methods do not exist. Useevents.getEventListeners().