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.
Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.
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.
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.
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With