How to use EventEmitter in Node.js?

The built-in events module is used by Node.js for dealing with events. This module provides the EventEmitter class using which you create and handle custom events.

You don't need to install anything to use the events module because it is one of the core Node.js APIs.

Here is how you import the events module in your code:

const EventEmitter = require('events');

After importing the events module, you have to either create an object of the EventEmitter class or extend a class with EventEmitter.

//Method 1
let eventEmitter = new EventEmitter();

//Method 2
class MyClass extends EventEmitter{
  //class body
}
let obj = new MyClass();

When an event occurs, it is said to be emitted. You trigger the event by calling the emit() method on the EventEmitter object.

eventEmitter.emit('event_name', [arg1], [arg2], ..., [argn])
  • You pass the name of the event to the emit() method.
  • The emit() method also accepts optional arguments that are passed to the event listeners.

The handler that listens to the event is called the listener. You must register a listener so that the desired actions can be taken when an event occurs.

The listener calls the callback function whenever an event occurs. You register a listener using the on() or addListener() method of the EventEmitter object.

eventEmitter.on('event_name', (arg1, arg2, ..., argn) => {
  //action to be taken
})
eventEmitter.addListener('event_name', (arg1, arg2, ..., argn) => {
  //action to be taken
})

The event_name of the on() method must match with the event_name passed to the emit() method.

Arguments that are passed to the emit() method are received by the listener as arguments to the callback function.

EventEmitter Node.js Examples

Suppose there is a data event that we want to handle. We start by importing the events module and then create an object of the EventEmitter class. After that, we register a listener to the data event. In the end, we trigger the data event.

const EventEmitter = require('events');

let eventEmitter = new EventEmitter();

eventEmitter.on('data', () => {
  console.log('Data event handled.');
});

console.log('Before event is triggerd.');
eventEmitter.emit('data');
console.log('After event is triggerd.');

Output

Before event is triggerd.
Data event handled.
After event is triggerd.

You can also pass additional information to the event handler using the optional arguments of the emit() method. For example, let's say there is a timer event, and you want to pass start and stop timing values to the event handler. In that case, you pass the values like this:

const EventEmitter = require('events');

let eventEmitter = new EventEmitter();

eventEmitter.on('timer', (start, stop) => {
  console.log(`Starting value: ${start}`);
  console.log(`Stopping value: ${stop}`);
});

eventEmitter.emit('timer', 10, 25);

Output

Starting value: 10
Stopping value: 25

Note: An event can have more than one listener. Listeners are executed in the order they are registered.

const EventEmitter = require('events');

let eventEmitter = new EventEmitter();

eventEmitter.on('data', (x, y) => {
  console.log('First Listener');
  console.log(`x = ${x}`);
  console.log(`y = ${y}`);
});

eventEmitter.on('data', (x, y) => {
  console.log('Second Listener');
  console.log(`x = ${x}`);
  console.log(`y = ${y}`);
});

eventEmitter.emit('data', 'JavaScript', 123);

Output

First Listener
x = JavaScript
y = 123
Second Listener
x = JavaScript
y = 123

Many built-in and third-party packages in Node.js use the events package for handling events. For example, one of the popular packages that use EventEmitter is socket.io. In scoket.io, you handle the connection event, which is fired when a user connects to the server.

Server-side code

const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

Client-side code

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>

Recommended Posts