Node.js Events

abhay singhabhay singh
1 min read

Node.js is the ideal platform for event-driven apps

Using Node.js events

On a computer, every action is an event. similar to the opening of a file or establishing a connection.

Node.js comes with an integrated module named "Events" that allows you to design, fire, and listen for your own events.

Use the require() function to add the built-in Events module. Additionally, an EventEmitter object instance is used for all event properties and methods. Make an EventEmitter object to gain access to these properties and methods:

Add Listener: EventEmitter.addListener(event, listener) adds a listener to an event. For the provided event, it adds the listener to the end of the array of listeners. If you make repeated calls to the same event and listener, the listener will be added more than once and will consequently fire more than once. Calls can be chained because both functions return emitter.

Remove Listener: The eventEmitter.removeListener() method removes the specified listener from the array of listeners that are subscribed to the given event by taking two arguments, event and listener. While eventEmitter.removeAllListeners() eliminates every subscribed listener from the array for the specified event.

Example:

const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
//Add a listener
eventEmitter.addListener(event, listener)
//Remove the listener
eventEmitter.removeListener(event, listener)
0
Subscribe to my newsletter

Read articles from abhay singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

abhay singh
abhay singh