Node.js - event emitter

0 points
Created by:

In this article, we would like to show you event emitter in Node.js.


On the backend side, Node.js offers the option to build a system similar to JavaScript events in the browser such as mouse clicks, keyboard button presses, etc. This can be achieved using the Node.js events module.

Practical example

The Node.js events module provides the EventEmitter class that is used to handle events.

1. Import EventEmitter using require():

const EventEmitter = require('events');

2. Initialize EventEmitter object:

const eventEmitter = new EventEmitter();

3. The object provides various methods. The most used are:

  • on - adds a callback function  to be executed when the event is triggered,
  • emit - triggers an event.

Below we create a simple connect event that displays information about connection in the console.

const EventEmitter = require('events');

// initialize object
const eventEmitter = new EventEmitter();

// create callback function
eventEmitter.on('connect', () => {

// trigger the event



See also

  1. JavaScript - custom event listener class

  2. TypeScript - custom event listener class


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂