Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to All Emitted Events in Node.js

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.

like image 991
Chris W. Avatar asked Mar 03 '11 09:03

Chris W.


People also ask

What is event listener in node JS?

Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.

How do I use event emitter in node JS?

Many objects in a Node emit events, for example, a net. Server emits an event each time a peer connects to it, an fs. readStream emits an event when the file is opened. All objects which emit events are the instances of events.

What is Libuv in Nodejs?

libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It supports epoll(4) , kqueue(2) , Windows IOCP, and Solaris event ports. It is primarily designed for use in Node. js but it is also used by other software projects.

What is dispatcher in node JS?

It facilitates interaction between objects in Node. A Dispatcher is a service object that is used to ensure that the Event is passed to all relevant Listeners.


2 Answers

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.

like image 144
Martin Avatar answered Oct 13 '22 00:10

Martin


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); }); 
like image 34
Henrik Joreteg Avatar answered Oct 12 '22 22:10

Henrik Joreteg