Node.js Event Handling Explained with Examples

Event Handling in Node.js

JavaScript mostly manages user-generated events, like mouse movements or button clicks, when it is employed inside an HTML

Each event in Node.js can be attached to a callback function, which gets executed when the event occurs. The Node.js runtime continuously listens for events and triggers the respective callbacks accordingly.

The Event Emitter Class

Event-driven programming is made possible by the EventEmitter class, which is provided by the events module in Node.js. One or more listeners (callback functions) can be connected to events of a certain type that are emitted by an EventEmitter object. All related callbacks run in the order they were registered when the event is released.

Steps to Handle Events in Node.js

  1. Import the events module.
  2. Create an instance of Event Emitter.
  3. Bind an event handler to a specific event.
  4. Emit the event when required.

Example: Using Event Emitter

javascriptCopyEdit// Import events module
var events = require('events');

// Create an EventEmitter object
var eventEmitter = new events.EventEmitter();

// Create an event handler
var connectHandler = function connected() {
   console.log('Connection successful.');
};

// Bind the connection event to the handler
eventEmitter.on('connection', connectHandler);

// Bind another event using an anonymous function
eventEmitter.on('data_received', function() {
   console.log('Data received successfully.');
});

// Fire events
eventEmitter.emit('connection');
eventEmitter.emit('data_received');

console.log("Program Ended.");

Output

Connection successful.
Data received successfully.
Program Ended.

Asynchronous File Handling in Node.js

In a Node.js application, a callback is usually accepted as the final parameter for any asynchronous function. The result is the second argument passed to the callback function, and the error (if any) is the first.

Example: Reading a File Asynchronously

First, create a text file named input.txt with the following content:

This is a thefullstack
designed to explain concepts in an easy and structured manner.

Now, create a JavaScript file named main.js with the following code:

javascriptCopyEditvar fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) {
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});

console.log("Program Ended");

Explanation

  • A file can be read asynchronously using the fs.readFile() function.
  • It is supplied as the callback’s initial argument in the event of an error.
  • The contents of the file are printed if it is successfully read.
  • Instead of waiting for the file reading to finish, the application prints “Program Ended” before showing the contents of the file.

Expected Output

Program Ended
This is a thefullstack
designed to explain concepts in an easy and structured manner.


It might be helpful:

What’s New in Node.js 21/22? 

Best Practices for API Design in Full-Stack Development

What is REST API with an example?

Error: Contact form not found.

₹25,000.00

SAP SD S4 HANA

SAP SD (Sales and Distribution) is a module in the SAP ERP (Enterprise Resource Planning) system that handles all aspects of sales and distribution processes. S4 HANA is the latest version of SAP’s ERP suite, built on the SAP HANA in-memory database platform. It provides real-time data processing capabilities, improved…
₹25,000.00

SAP HR HCM

SAP Human Capital Management (SAP HCM)  is an important module in SAP. It is also known as SAP Human Resource Management System (SAP HRMS) or SAP Human Resource (HR). SAP HR software allows you to automate record-keeping processes. It is an ideal framework for the HR department to take advantage…
₹25,000.00

Salesforce Administrator Training

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
₹25,000.00

Salesforce Developer Training

Salesforce Developer Training Overview Salesforce Developer training advances your skills and knowledge in building custom applications on the Salesforce platform using the programming capabilities of Apex code and the Visualforce UI framework. It covers all the fundamentals of application development through real-time projects and utilizes cases to help you clear…
₹25,000.00

SAP EWM

SAP EWM stands for Extended Warehouse Management. It is a best-of-breed WMS Warehouse Management System product offered by SAP. It was first released in 2007 as a part of SAP SCM meaning Supply Chain Management suite, but in subsequent releases, it was offered as a stand-alone product. The latest version…
₹25,000.00

Oracle PL-SQL Training Program

Oracle PL-SQL is actually the number one database. The demand in market is growing equally with the value of the database. It has become necessary for the Oracle PL-SQL certification to get the right job. eLearning Solutions is one of the renowned institutes for Oracle PL-SQL in Pune. We believe…
₹25,000.00

Pega Training Courses in Pune- Get Certified Now

Course details for Pega Training in Pune Elearning solution is the best PEGA training institute in Pune. PEGA is one of the Business Process Management tool (BPM), its development is based on Java and OOP concepts. The PAGA technology is mainly used to improve business purposes and cost reduction. PEGA…
₹27,000.00

SAP PP (Production Planning) Training Institute

SAP PP Training Institute in Pune SAP PP training (Production Planning) is one of the largest functional modules in SAP. This module mainly deals with the production process like capacity planning, Master production scheduling, Material requirement planning shop floor, etc. The PP module of SAP takes care of the Master…

X
WhatsApp WhatsApp us
Call Now Button