NodeJS EventEmitter in Routes

Ridwan Olalere (Didi Kwang)
2 min readApr 11, 2015

--

If you are going to use NodeJS EventEmitter to listen to and emit events in your NodeJS application then you need to know this:

  1. The same EventEmitter instance used to emit the event must be used to listen to event.

What that means is that you can not create an instance of EventEmitter in your route or anywhere else to emit event and use another instance of EventEmitter to listen to the event. It won’t work.

So How to do you pass the same instance of EventEmitter in your application.

My Approach

While working on http://bestprices.ng, I wanted to use EventEmitter to announce specific events when they occur and use the same EventEmitter in the hook system to listen to those events then do something else. For example when a new product review is published EventEmitter should emit ‘review-created’ and any hook subscribed to the event can post the review to social network sites or even ping it to search engines.

In order to pass the same instance of EventEmitter around in my routes I used:

app.set(<name>, <value>)

app.set assigns the name to value. The trick here is that the value can be anything — js object, string, boolen, number.

In my app.js file I created the only event instance to be used for listening and emtting

var e = require(‘events’)
var events = new e.EventEmitter();
app.set('event', events);

Now that the event has been instantiated in the app.js file we can use it in any of our routes function as seen below:

function(req, res){var event = req.app.get(‘event’);event.emit('user-created', {});}

The variable event in the code above can be used to emit any kind of event and can also be used to listen to any of the emitted events. Cheers!!

Below is code to listen to the event somewhere else:

function(event){event.on(‘user-created’, function(data){
//do anything here with the data passed
})}

At http://bestprices.ng, we are constantly working on how to make product price comparison and discovery easy for online shoppers in Nigeria.

You can follow me on twitter @ridwan_olalere for more development help.

--

--