Introduction
This article explains the EventEmitter in NodeJS. To access the EventEmitter class, use:
require('events').EventEmitter
API methods are accessed through an instance of the EventEmitter class. For this you need to create an object of the EventEmitter class, then you can access the method.
For example
var obj=new EventEmitter();
Using that you can access the API method via an EventEmitter instance. Let's see how in the following:
obj.emitEvent();
In Node, we do not have the DOM so we use the EventEmitter class. This class has mainly two methods, "on" and "emit". I have given the example and sample use of these methods in the NodeJS environment.
EventEmitter Class
The event module contains the EventEmitter class. The Util package provides a way to inherit from one class to another class. The "EventEmitter" class allows us to listen for events and assign actions to run when those events occur. The EventEmitter class is based on a publish/subscribe model because we can subscribe to events and then publish them.
When we use the EventEmitter class we need to require an events module in the program, for example:
var ev=require("events");
The ev object will then have a single property, which is the EventEmitter class itself.
Objects that emit events are instances of "events.EventEmitter." You can access them using:
require("events")
Functions can be attached to objects, to be executed when an event is emitted; these functions are listeners. Inside a listener function, "this" refers to the "EventEmitter" that the listener was attached to.
Let's see a simple example of the EventEmitter class. Create a file with a .js extension and execute the code in a Node.js command prompt.
Step 1
Open the editor and write the following code and save the file with a .js extension as in the following figure:

Step 2
Now open the node.js command prompt. If you don't have the node.js environment then you can download it from this link Get NodeJS Framework.






Comments
Join the conversation! Your thoughts help the community grow.