Listen to All Emitted Events in Node.js

后端 未结 12 1322
孤街浪徒
孤街浪徒 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:32

    a monkey patch add onAny method to EventEmitter.

    it is useful to be able to monitor only events of one problem.

    var EventEmitter=require('events')
    var origemit=EventEmitter.prototype.emit;
    Object.assign( EventEmitter.prototype, {
      emit:function(){
        if(this._onAnyListeners){
            this._onAnyListeners.forEach((listener)=>listener.apply(this,arguments))
        }
        return origemit.apply(this,arguments)
      },
      onAny:function(func){
        if(typeof func !== 'function'){
          throw new Error('Invalid type');
        }
        if(!this._onAnyListeners)this._onAnyListeners=[];
        this._onAnyListeners.push(func);
      },
      removeOnAny:function(func){
        const index = this._onAnyListeners.indexOf(func);
        if(index === -1){
          return;
        }
        this._onAnyListeners.splice(index,1);
      }
    });
    // usage example
    //gzip.onAny(function(a){console.log(a)})
    

提交回复
热议问题