Node.js Events

Node.js Events

Understanding events in Node.js

Node.js is an Asynchronous event-driven JavaScript runtime. It has event-driven architecture which performs asynchronous tasks. Node.js has one built-in module i.e. Node.js event module which allows us to create and handle our own events.

Let's create a file with practice.js name. Since Node.js event module is a built-in module so we don't need to install it into our computer. Only thing we have to do is to incorporate it in our practice.js file such as

const events = require('events');

Node.js events module offers the EventEmmiter class. The instance of this class has all the event properties & methods which are used to create and handle events. Let's create the eventEmmiter, instance of EventEmmiter class such as

const eventEmmiter = new events.EventEmitter();

Let's create a callback function which subscribe to a specific event and when that event triggers, this function is called.

const callback = function() {
    console.log('I hear a sound');  
}

Now, let's subscribe the recently created callback function(callback) to the event 'sound' with the help of on() method on eventEmmiter.

eventEmmiter.on('sound', callback);

Now. let's fire our 'sound' event using emit() method,

eventEmmiter.emit('sound');

Run this practice.js script by executing following command in terminal

$ node practice.js

On running this script, the 'sound' event is fired which triggers the event and then subscribed callback function is called which logs the 'I hear a sound' in console such as

Screenshot (87).png

That's a simple illustration of events in Node.js.

Happy learning.