Explain Event-Driven Programming in Node.js

19 Oct, 2021
Event-Driven Programming in Node.js: Node.js makes extensive use of events which is one of the reasons behind its speed when compared to other similar technologies. Once we start a Node.js server, it initializes the variables and functions and then listens for the occurrence of an event.
Event-driven programming is used to synchronize the occurrence of multiple events and to make the program as simple as possible. The basic components of an Event-Driven Program are:
A callback function ( called an event handler) is called when an event is triggered.
An event loop that listens for event triggers and calls the corresponding event handler for that event.
A function that listens for the triggering of an event is said to be an ‘Observer’. It gets triggered when an event occurs. Node.js provides a range of events that are already in-built. These ‘events’ can be accessed via the ‘events’ module and the EventEmitter class. Most of the in-built modules of Node.js inherit from the EventEmitter class
EventEmitter: The EventEmitter is a Node module that allows objects to communicate with one another. The core of Node’s asynchronous event-driven architecture is EventEmitter. Many of Node’s built-in modules inherit from EventEmitter.
The idea is simple – emitter objects send out named events, which trigger listeners that have already been registered. Hence, an emitter object has two key characteristics:
Emitting name events: The signal that something has happened is called emitting an event. A status change in the emitting object is often the cause of this condition.
Registering and unregistering listener functions: It refers to the binding and unbinding of the callback functions with their corresponding events.
Event-Driven Programming Principles:
A suite of functions for handling the events. These can be either blocking or non-blocking, depending on the implementation.
Binding registered functions to events.
When a registered event is received, an event loop polls for new events and calls the matching event handler(s).
Implementation:  Filename: app.js
Javascript
// Import the 'events' moduleconst events = require('events');  // Instantiate an EventEmitter objectconst eventEmitter = new events.EventEmitter();  // Handler associated with the eventconst connectHandler = function connected() {    console.log('Connection established.');      // Trigger the corresponding event    eventEmitter.emit('data_received');}  // Binds the event with handlereventEmitter.on('connection', connectHandler);  // Binds the data receivedeventEmitter.on(    'data_received', function () {        console.log('Data Transfer Successful.');    });  // Trigger the connection eventeventEmitter.emit('connection');  console.log("Finish");
The above code snippet binds the handler named ‘connectHandler’ with the event ‘connection’’. The callback function is triggered when the event is emitted.
Run the app.js file using the following command:
node app.js
Output:  
Connection established.
Data Transfer Successful.
Finish
Advantages of Event-Driven Programming:
Flexibility: It is easier to alter sections of code as and when required.
Suitability for graphical interfaces: It allows the user to select tools (like radio buttons etc.) directly from the toolbar
Programming simplicity: It supports predictive coding, which improves the programmer’s coding experience.
Easy to find natural dividing lines: Natural dividing lines for unit testing infrastructure are easy to come by.
A good way to model systems: Useful method for modeling systems that must be asynchronous and reactive.
Allows for more interactive programs: It enables more interactive programming. Event-driven programming is used in almost all recent GUI apps.
Using hardware interrupts: It can be accomplished via hardware interrupts, lowering the computer’s power consumption.
Allows sensors and other hardware: It makes it simple for sensors and other hardware to communicate with software.
Disadvantages of Event-Driven Programming:
Complex: Simple programs become unnecessarily complex.
Less logical and obvious: The flow of the program is usually less logical and more obvious
Difficult to find error: Debugging an event-driven program is difficult
Confusing: Too many forms in a program might be confusing and/or frustrating for the programmer.
Tight coupling: The event schema will be tightly coupled with the consumers of the schema.
Blocking: Complex blocking of operations.
Relation between Event-Driven Programming and Object-Oriented Programming: We can combine Object-oriented Programming (OOP) and Event-driven programming (EDP) and use them together in the same code snippet.
When OOP is used with EDP:  
All OOP fundamentals (encapsulation, inheritance, and polymorphism) are preserved.
Objects get the ability to post-event notifications and subscribe to event notifications from other objects.
How to distinguish between OOP with and without EDP: The control flow between objects is the distinction between OOP with and without EDP. On a method call in OOP without EDP, control flows from one object to another. The primary function of an object is to call the methods of other objects.
However, on event notification, control in OOP with EDP moves from one object to another. Object subscribes to notifications from other objects, waits for notifications from those objects, performs work based on the notification, and then publishes its own notifications.
NodeJS-Questions
Picked
TrueGeek-2021
Node.js
TrueGeek
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.