Languages
[Edit]
EN

Node.js - event emitter

0 points
Created by:
Majid-Hajibaba
402

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

Introduction

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', () => {
    console.log('connected');
});

// trigger the event
eventEmitter.emit('connect');

Output:

connected

See also

  1. JavaScript - custom event listener class

  2. TypeScript - custom event listener class

References

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.

❤️💻 🙂

Join