EN
Node.js - event emitter
0 points
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.
The Node.js events module provides the EventEmitter
class that is used to handle events.
1. Import EventEmitter
using require()
:
xxxxxxxxxx
1
const EventEmitter = require('events');
2. Initialize EventEmitter
object:
xxxxxxxxxx
1
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.
xxxxxxxxxx
1
const EventEmitter = require('events');
2
3
// initialize object
4
const eventEmitter = new EventEmitter();
5
6
// create callback function
7
eventEmitter.on('connect', () => {
8
console.log('connected');
9
});
10
11
// trigger the event
12
eventEmitter.emit('connect');
Output:
xxxxxxxxxx
1
connected