Node JS Events module and EventEmitter

Node JS Events module and EventEmitter

Featured, Javascript, Node JS

Hi Coders, Today we are going to discuss about node.js events module and everything you need to know about event emitters in node.js

What is a Event ?

When a user interacts on webpage or press a key or scroll a website, these all interactions are called event. When a event occurs it checks for a event handler attached to it, if yes then it calls the event handlers in the respective order. Some Javascript events are listed below

EventEvent Handler
clickonclick
mouseoveronmouseover
mousedownonmousedown

Event Module in Node JS

As we know node works on event driven architecture and we can achive event driven programming using event module in node js. To use event we need to do the following

const events = require('events');

The event module includes the EventEmitter class which is used to handle events in Node JS

Event Emitters

EventEmitter is a class which provides us publisher-subscriber pattern in Node JS. Using Event Emitter we can publish an event, we can add a listener to it which listen to the raised event and take the necessary action.

We can create EventEmitter class as shown below.

const { EventEmitter } = require('events');

class Calculator extends EventEmitter{ }

Publish Events and Listen to them

To understand event publish and how we will add listener to it we are going to create a calculator using EventEmitter class.

const { EventEmitter } = require('events');

class Calculator extends EventEmitter{
    constructor(a,b){
        super();
    }

    calculate(a,b){
        setTimeout(()=>{
            let sum = a + b;
            this.emit('calculate',sum);
            console.log("the event emitted after 3 seconds");
        },3000)
    }
   
}

const myCalculator = new Calculator();

myCalculator.on('calculate',response =>{
    console.log(`calculated value is ${response}`);
});

myCalculator.calculate(7,3);

In the above program we have extended EventEmitter class in Calculator class to create a event calculate in calculate method. We have registered a listener using the instance of Calculator class just above the method we have called.

The above program will give us addition of input numbers after 3 seconds.

We have used setTimeout() in the method to show you that once a event is emit after 3 seconds it will check the registered listener and calls it to give the response back .

Methods in Event Module

  1. emit(event, [arg1], [arg2], […]) : It executes the listener with the supplied arguments, returns true if the event has a listener.
  2. on(event, listener) : Adds a listener on the emitted event.
  3. once(event, listener) : Adds a one time listener, It gets removed after fired once.
  4. addListener(event, listener) : Adds a listener at the end of the listeners array.
  5. removeListener(event, listener) : Removes the listener from listeners array
  6. removeAllListeners([event]) : Removes all listeners, or those of the specified event.

I am adding one more EventEmitter program to demonstrate the functions we have discussed above.

const { EventEmitter } = require('events');

class countDown extends EventEmitter{
    constructor(countDownTime){
        super();
        this.countDownTime = countDownTime;
        this.currentTime = 0;
    }

    startTimer(){
        const timer = setInterval(() => {
            this.currentTime++;
            this.emit('update', this.currentTime);
            this.emit('update-once', this.currentTime);

            if(this.currentTime == this.countDownTime){
                clearInterval(timer);
                this.emit('end');
            }

            if (this.currentTime === this.countDownTime - 2) {
                this.emit('end-soon');
            }

        }, 2000)
    }
}

const myCountDown = new countDown(5);

myCountDown.on('update',(timer) => {
    console.log(`${timer} seconds has been passed since the timer started`)
})


myCountDown.once('update-once',(timer) => {
    console.log(`${timer} seconds and this listener will run only once.`)
})

myCountDown.addListener('end', () => {
    console.log('Countdown is completed');
});

myCountDown.on('end-soon', () => {
    console.log('Count down will be end in 2 seconds');
});

console.log(myCountDown.eventNames());
console.log(myCountDown.getMaxListeners()) // default to 10

myCountDown.startTimer();

Where Node JS Internally uses Event Emitters

Node js widely use event emitters in its whole environment .

Streams in Node js extends event emitter and have predefined events like open, data, error, end

Other example is Node js process object which is used globally in node environment. It has events like exit, uncaughtException

Conclusion:

This is all i have for you on events for now. We have tried to cover all the important topics of events . Let me know in response section if i missed some.

References :

https://nodejs.dev/learn/the-nodejs-events-module

Node.Js Articles you might like …

Leave a Reply