In Node.js is there any way to listen to all events emitted by an EventEmitter object?
e.g., can you do something like...
event_emitter.on(\
I needed to trace all emitted events in all libraries, so I tapped into the prototype.
This example uses a Typescript signature, but you can just remove it if you are not into that kind of nonsense.
Within the call, this refers to the object that is emitting. It was very easy to track all unique object:emits in my project.
// For my example I use a `set` to track unique emits.
const items = new Set()
const originalEmit = EventEmitter.prototype.emit;
EventEmitter.prototype.emit = function (event: String | Symbol, ...args: any[]): boolean {
// Do what you want here
const id = this.constructor.name + ":" + event;
if (!items.has(id)) {
items.add(id);
console.log(id);
}
// And then call the original
return originalEmit.call(event, ...args);
}
You can very easily extend this and filter based on event name or class name.