Find your content:

Search form

Learn node.js simple way - Event Emitter

 
Share

Node.js uses event driven programming in large amount. Whenever you create a method with callback it is one kind of event. Once task execution is done, it invoke the callback method to inform the user that task is completed. What happen if multiple users are accessing the application and multiple events are fired? To prioritize the list of events, Node.js uses event loop which keep the queue and executes one by one based on the architecture.

How to create a Event?

Node.js comes up with built in module called "events". We need to import this module and create a new event. Refer below example. Create a file "eventemitter.js"

var events = require("events");

//Create a object for eventemitter
var eventemitter = new events.EventEmitter();

//Define an event with callback.
eventemitter.on('msg_sent', function(){
  console.log("Msg sent");
});

//Call the event
eventemitter.emit("msg_sent");
console.log("Done");

 

Lets run this program.

node eventemitter.js

you get the below output

Msg sent
Done

comment out the eventemitter.emit("msg_sent"); line and run the program.

var events = require("events");

//Create a object for eventemitter
var eventemitter = new events.EventEmitter();

//Define an event with callback.
eventemitter.on('msg_sent', function(){
  console.log("Msg sent");
});

//Call the event
// eventemitter.emit("msg_sent");
console.log("Done");

 

You get the below output

Done

eventemitter.emit responsible for calling the defined event.

What else we can do using eventemitter?

It has a several methods which can be used based on the context.I am listing out few...

Method NameDescription
addListener(event, listener)New listener will be added in the end of the array.
once(event, listener)Thiswill be fired only once and removed after that.
removeListener(event, listener)Listener will be removed
setMaxListeners(nums)Default is 10, if you want to increase use this method.

 

 

My Block Status

My Block Content