Node.js Reference ยท Events and Timers
Node.js emitter.off() method
Reference for emitter.off(), removeListener() and removeAllListeners() in Node.js: which listener is removed, the removeListener event and cleanup patterns.
emitter.off(eventName, listener) removes a previously registered listener. removeListener() is the same method under its older name. To remove every listener of one event, or of the whole emitter, use removeAllListeners().
Removal matches by function identity, so you must pass the very same function you registered. That is why listeners you intend to remove should be named functions or stored in variables, not inline arrows.
emitter.off('data', onData);
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.off(eventName: string | symbol, listener: Function): this emitter.removeListener(eventName: string | symbol, listener: Function): this emitter.removeAllListeners(eventName?: string | symbol): this
| Name | Description |
|---|---|
eventName |
The event whose listener should be removed. |
listener |
The function previously registered. For once() listeners, pass the original function. |
Returns: the emitter.
Errors: ERR_INVALID_ARG_TYPE if listener is not a function. Removing a listener that is not registered is silently ignored.
Usage notes
- One instance per call. If a function was added three times, you need three
off()calls. Each removes the instance added most recently (the one closest to the end). 'removeListener'event. After each removal Node emits'removeListener'with(eventName, listener), if anyone listens.removeAllListeners()with no argument removes the'removeListener'listeners last, so they are told about every other removal but not about their own.- During an emit. A listener removed while an
emit()is running still runs in that emit, because the list was copied first; it is gone in the next one. removeAllListeners()is broad. Calling it on an emitter you do not own (a stream, a socket,process) can remove listeners Node or a library depends on. Prefer removing your own function.- Preventing leaks. Every
on()in a function that runs many times should have a matchingoff(). Long-lived emitters collect listeners over time otherwise; see setMaxListeners(). - Signals.
events.once()andevents.on()accept anAbortSignalthat removes their listeners for you. - Added in:
off()is an alias added in Node.js 10; it behaves identically toremoveListener().