CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Node.js – Events – A brief discussion

As discussed in our previous article, “Node.js – An Introduction“; it uses a Single Thread Event model to handle concurrent client requests.

That said, Node.js supports an event-driven model to handle the requests. Some kind of objects periodically issues the events, and some objects will listen to these events. The objects that emit the events are called “emitters” and the objects that listen to the events are called “listeners”.

The listener’s methods will be attached to the events and these will be called synchronously whenever an event is triggered. This is important to execute the functions attached to the listeners, in an order to avoid any logic errors or race conditions. That doesn’t mean that listener functions are always called synchronously; there are cases, where asynchronous operations are required and then listeners can switch the mode to asynchronous.

The best example of an event is, an Error event; emitted when something went wrong during Program execution and it is good practice to add listeners to handle the error events to avoid program termination.

EventEmitter class is used to define the objects to emit or issue the events. It has on() method (or addListener), which is used to attach one or more functions to named events issued by the emitter object. This class is defined in events module.

When the event is triggered it carries some details and these can be passed as an argument to the listeners using the emitter object’s emit() function.

</> Michael

Node.js – Events – A brief discussion

2 thoughts on “Node.js – Events – A brief discussion

Leave a Reply

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

Scroll to top
Exit mobile version