How to remove ALL event listeners in NodeJS EventEmitter?

18,248

Perhaps the simplest way would be to just replace the eventEmitter object with a new one that would have no listeners registered on it.

If you really need to clear all registered events because other code has a reference to the current emitter object, then you can do it using the public API like this:

emitter.removeAllListeners();

Which is described in the node.js doc here. That function can pass an event name to remove all listeners just for that event or, if no event name is passed, it removes all listeners for all events.

FYI, you can also get all event names that have any registered event handlers with the emitter.eventNames() method and then you can remove all listeners for any given event name with emitter.removeAllListeners(eventName). So, you could also iterate through all the event names and remove all listeners for any of them you wanted to.

Share:
18,248

Related videos on Youtube

Maxmaxmaximus
Author by

Maxmaxmaximus

Updated on September 16, 2022

Comments

  • Maxmaxmaximus
    Maxmaxmaximus over 1 year

    How to remove ALL event listeners in NodeJS?

    • Andrew Li
      Andrew Li almost 7 years
      When the editor gives you a warning that there are not enough characters, don't just spam the same question over and over again. Listen to what it says and describe your problem in more detail.
    • Pim van der Heijden
      Pim van der Heijden almost 3 years
      I don't recommend removing ALL event listeners