Node.js Event Handling Explained with Examples

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?

admin
admin
https://www.thefullstack.co.in

Leave a Reply