Listen to All Emitted Events in Node.js

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

    Since Node.js v6.0.0, the new class syntax and argument spread operator is fully supported, so it's pretty safe and fairly easy to implement the desired functionality with simple inheritance and an method override:

    'use strict';
    var EventEmitter = require('events');
    
    class MyEmitter extends EventEmitter {
      emit(type, ...args) {
        super.emit('*', ...args);
        return super.emit(type, ...args) || super.emit('', ...args);
      }
    }
    

    This implementation relies on the fact that the original emit method of the EventEmitter returns true/false depending if the event was handled by some listener or not. Notice that the override includes a return statement, so we keep this behavior for other consumers.

    Here the idea is to use the star event (*) to create handlers that gets executed on every single event (say, for logging purposes) and the empty event ('') for a default or catch all handler, that gets executed if nothing else catches that event.

    We make sure to call the star (*) event first, because in case of error events without any handlers, the result is actually an exception being thrown. For more details, take a look at the implementation of the EventEmitter.

    For example:

    var emitter = new MyEmitter();
    
    emitter.on('foo', () => console.log('foo event triggered'));
    emitter.on('*', () => console.log('star event triggered'));
    emitter.on('', () => console.log('catch all event triggered'));
    
    emitter.emit('foo');
        // Prints:
        //   star event triggered
        //   foo event triggered
    
    emitter.emit('bar');
        // Prints:
        //   star event triggered
        //   catch all event triggered
    

    Finally, if an EventEmitter instance already exists but you want to adjust that specific instance to the new behavior, it can be easily done by patching the method at runtime like this:

    emitter.emit = MyEmitter.prototype.emit;
    

提交回复
热议问题