Skip to content

Instantly share code, notes, and snippets.

@srsandy
Last active May 23, 2018 13:16
Show Gist options
  • Save srsandy/9e27dbfa3d2086aedda964a67742c140 to your computer and use it in GitHub Desktop.
Save srsandy/9e27dbfa3d2086aedda964a67742c140 to your computer and use it in GitHub Desktop.
Events in NodeJS

EventEmitter() in NodeJS 😄

EventEmitter is a class in NodeJS that helps to listen or fire events in your application. You can also keep track of events in you application.

Let's start with a simple eventEmitter example. First of all we need to add Event Object in our project

const events = require('events');
var eventEmitter = new events.EventEmitter();

The following example shows a simple EventEmitter instance with a single listener. The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.

eventEmitter.on('msg', function() {
  console.log('An event was emitted');
});

eventEmitter.emit('msg');

eventEmitter.on() method takes the event's name and a callback function that needs be fire when the event is emitted by the emit() method. eventEmitter.emit() method takes the event name to be called and you can also pass some arguments that can be used by our event callback function.

You can also call an event after some intervals by using setInterval(). You can also chain multiple events and call them when required.

eventEmitter.on('msg-1', function() {
  console.log('An event-1 was emitted');
}).on('msg-2', function() {
  console.log('An event-2 was emitted');
});

eventEmitter.emit('msg-1');
eventEmitter.emit('msg-2');

Note: You can use ES6 arrow functions in the callbacks.

Passing arguments

eventEmitter.on('event', function(a, b) {
  console.log(a, b, this);
});

eventEmitter.emit('event', 'a', 'b');

// Prints:
// >   a b eventEmitter {
// >    domain: null,
// >   _events: { event: [Function] },
// >   _eventsCount: 1,
// >   _maxListeners: undefined } 

In the above E.g we console.log(this); which points to that the standard this keyword is intentionally set to reference the EventEmitter instance to which the listener is attached.

eventEmitter.on('event', (a, b) => {
  console.log(a, b, this);
});

eventEmitter.emit('event', 'a', 'b');
// Prints
// > a b {}

When we use arrow functions this keyword will no longer reference the EventEmitter instance. To have the EventEmitter instance in this case you will need to call(this) inside the .on() method by adding events.EventEmitter.call(this);.

Different types of Listeners

Apart of .on() we've other types of listeners.

  • eventEmitter.addListener(eventName, listener): This is an alias for eventEmitter.on(eventName, listener).

  • eventEmitter.once(eventName, listener): It adds one-time listener function to the eventName. If ever the eventName is emitted again the listener is removed unregistered and then called.

    E.g.

      let m = 0;
      eventEmitter.once('event', () => {
        console.log(++m);
      });
      eventEmitter.emit('event');
      // > 1
      eventEmitter.emit('event');  // Ignored
  • eventEmitter.prependListener(eventName, listener): Adds a listener to the top of the array for the event named eventName. Calling the same combination of eventName the listener function multiple times, this will result in the addition of the listener function multiple times at the top of the array.

    E.g

      eventEmitter.once('an-event', () => console.log('I will be called Once.'));
      eventEmitter.prependOnceListener('an-event', () => console.log('I will be called 1st.'));
      eventEmitter.prependOnceListener('an-event', () => console.log('I will be called 1st.'));
      eventEmitter.emit('an-event');
      // > I will be called 1st.
      // > I will be called 1st.
      // > I will be called Once.
  • eventEmitter.prependOnceListener(eventName, listener): Adds a one-time listener to the top of the array for the event named eventName. If ever the eventName is emitted again the listener is removed unregistered and then called.

eventEmitter.removeListener(eventName, listener) & eventEmitter.removeAllListeners([eventName])

  var eventFun = () => console.log('This is an event \n');
  
  eventEmitter.on('event', eventFun);
  
  setInterval(function() {
    eventEmitter.emit('event');
  },2000);
  
  console.log(eventEmitter.eventNames());
  
  // > [ 'event' ]
  // >This is an event
  // >
  // > This is an event
  // >
  // > ...

So as you know the above code will .emit('event') after every 2s. Let's suppose you want to stop the firing of the event after 8s in such situations removeListener() comes handy as it removes the event from the events array. So we add.

  var eventFun = () => console.log('This is an event \n');
  
  eventEmitter.on('event', eventFun);
  
  setInterval(function() {
    eventEmitter.emit('event');
  },2000);
  
  console.log(eventEmitter.eventNames());
  
  setTimeout(function() {
    eventEmitter.removeListener('event', eventFun);
    console.log(eventEmitter.eventNames());
  }, 8000);
  
  // > [ 'event' ]
  // > This is an event
  // >
  // > This is an event
  // >
  // > This is an event
  // >
  // > []
  

As we called removeListener() after 8s .emit() fires the event 3 times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment