Node.js event emitter explained

nodejs
Image source:Pixabay

Node.js core API is based on asynchronous event-driven architecture in which certain kind of objects called emitters periodically emit events that cause listener objects to be called.

All objects that emit events are members of EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. All values returned by the called listeners are ignored and will be discarded.

Consider the following example:

Here we create a myEmitter object and emit event at the end which triggers the callback function and we are able to get the desired output.

By default, all listeners attached to a particular event object are called by the EventListener object synchronously in the order in which they are registered or attached to the event object.

If we want to break that flow and switch to asynchronous mode then we can use setImmediate() or process.nextTick() methods:

As we can see from the output of the above program,  the nextTick is called in the iteration after the task of displaying 1st log statement is executed and then in the next cycle of picking up event from event loop task defined in process.nextTick() is called while setImmediate allows running some task asynchronously.

Handling event calls in Node.js:

The listener can be invoked only once using eventEmitter.once() method while every time the event is emitted using eventEmitter.on() method:

This concludes today’s short tutorial on Node.js. You can follow my facebook page: TechnoeticsClub  to get notified about similar such posts in future. Till then keep coding and learning new stuff 😀

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development