Let’s discuss some of the core concepts of Node.js. It is a very short post, but it is very important, if you want to play around with Node.js. It will give you a fair amount of idea how the activity is raised and handled by this fascinating coding language. Let’s jump into the topic.

Events and Event Emitter in Node.js

Any kind of activity or action taking place in the computer world are called an event. Some of the examples of the event are like the connection to a database, file opening, receiving data, closing connection etc. Node.js has some pre-defined events. It also gives us the privilege to register new events and use as per our requirements.

Create an event :

As I mentioned before, We can create our own event and use as per our requirement. Node.js a built-in module called ‘events’. You can read more about it from Node.js documentation.

It is a class. you need to instantiate to use its feature. How you need to do that. Just have a look.

const EventEmitter = require('events');

//Creating object of EventEmitter class
const emitter = new EventEmitter();

Next step would register the event and attach a listener, which will react when the event is raised. For this, Node.js has given us two options.
1. on
2. addListner
Both are the same. Most of the time ‘on’ is used. We have seen this in jQuery as well.
Let’s see how to do this.

// registering a event and attaching listner to it
emitter.on('logData', function() {
    console.log('code is fine')
})

‘logData’ is the name of the event. After the name of the event, we have a function. This is a listener function, which will react when an event is raised/produced.

How to raise an event:

It is pretty simple. Below code will demonstrate it,

// creating or producting an event
emitter.emit('logData');

Below is the complete code to try out.


const EventEmitter = require('events');

//Creating object of EventEmitter class
const emitter = new EventEmitter();

// registering a event and attaching listner to it
emitter.on('logData', function() {
console.log('code is fine')
})

// creating or producting an event
emitter.emit('logData');

Note: Please remember to register event first, then emit or raise the event. Otherwise, you won’t see the desired result.

Please feel free to comment and share.