Reputation: 2189
How to remove ALL event listeners in NodeJS?
Upvotes: 24
Views: 26092
Reputation: 707238
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.
Upvotes: 36