Events in Node Js

Node Js is a asynchronous event-driven runtime. Node Js can perform tasks asynchronously, i.e. without waiting for a task to be executed, it can move further. Node Js has a built-in module named “events”. “events” module has EventEmitter() class. With the instance of EventEmitter() class we can handle multiple events. Every event takes a function as a callback, whenever the event occurs, the callback function get called. Every event is a named event. The callback functions are executed in the order, in which they are registered.

Example :

Code to handle events
Output

eventEmitter.on() and eventEmitter.addListener() works in similar way, but the eventEmitter.once() only executes the listener function once, after that it removes the callback function from the listener list.

Calling multiple listener functions for a single event

Leave a Reply

Your email address will not be published. Required fields are marked *