Listen to All Emitted Events in Node.js

后端 未结 12 1317
孤街浪徒
孤街浪徒 2020-12-24 00:06

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(\         


        
12条回答
  •  孤独总比滥情好
    2020-12-24 00:41

    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.

提交回复
热议问题