Listen to All Emitted Events in Node.js


Question

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('',function(event[, arg1][, arg2]...) {}

The idea is that I want to grab all of the events spit out by a server side EventEmitter, JSON.stringify the event data, send it across a websockets connection, reform them on the client side as an event, and then act on the event on the client side.

1
64
3/3/2011 9:34:12 AM

Accepted Answer

As mentioned this behavior is not in node.js core. But you can use hij1nx's EventEmitter2:

https://github.com/hij1nx/EventEmitter2

It won't break any existing code using EventEmitter, but adds support for namespaces and wildcards. For example:

server.on('foo.*', function(value1, value2) {
  console.log(this.event, value1, value2);
});
38
4/4/2012 8:34:12 PM

I know this is a bit old, but what the hell, here is another solution you could take.

You can easily monkey-patch the emit function of the emitter you want to catch all events:

function patchEmitter(emitter, websocket) {
  var oldEmit = emitter.emit;

  emitter.emit = function() {
      var emitArgs = arguments;
      // serialize arguments in some way.
      ...
      // send them through the websocket received as a parameter
      ...
      oldEmit.apply(emitter, arguments);
  }
}

This is pretty simple code and should work on any emitter.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon