The Power of Event-Driven Architecture: Why Node.js is Efficient and Popular

The Power of Event-Driven Architecture: Why Node.js is Efficient and Popular

Do you ever thought why Node.js is so much popular? Node.js is popular and efficient one of the reasons is its event-driven architecture. In traditional server-side programming models, each client request would be handled by a separate thread or process. This approach can quickly consume resources and lead to poor performance if many requests are processed simultaneously.

In contrast, Node.js uses a single-threaded, event-driven architecture, where each incoming request is treated as an event and is handled by an event loop. The event loop is responsible for managing all the asynchronous I/O operations in the application, such as network requests and file I/O. When an event occurs, the corresponding callback function is executed, and the event loop moves on to the next event.

This approach is efficient because it allows Node.js to handle a large number of requests simultaneously without the need for additional threads or processes. Since the event loop can switch between events quickly, the application can be very responsive even when handling a large number of requests. Additionally, the event-driven architecture makes it easy to write scalable and high-performance applications that can handle a large number of concurrent connections.

Let's see a basic application in Node.js based on event-driven architecture using events module.

const EventEmitter = require("events");

class ShoppingCart extends EventEmitter {
  constructor() {
    super();
    this.items = [];
  }

  addItem(item) {
    this.items.push(item);
    this.emit("itemAdded", item);
  }

  removeItem(item) {
    const index = this.items.indexOf(item);
    if (index >= 0) {
      this.items.splice(index, 1);
      this.emit("itemRemoved", item);
    } else {
      console.log(`${item} is not available in the cart`);
    }
  }

  getItems() {
    if (this.items.length <= 0) {
      console.log("No item is available in the cart");
    }
    return this.items;
  }
}

const cart = new ShoppingCart();

cart.on("itemAdded", (item) => {
  console.log(`Item ${item} has been added to the cart`);
});

cart.on("itemRemoved", (item) => {
  console.log(`Item ${item} has been removed from the cart`);
});

cart.addItem('Apple');
// // Output: Item Apple has been added to the cart

cart.addItem('Banana');
// Output: Item Banana has been added to the cart

cart.removeItem("Apple");
// Output: Item Apple has been removed from the cart

console.log(cart.getItems());
// // Output: [ 'Banana' ]

First, the events module is imported, which provides the EventEmitter class. The EventEmitter class is used to emit and listen to events within a Node.js application.

A new class named ShoppingCart is then created, which extends the EventEmitter class. This means that the ShoppingCart class can emit events that can be listened to by other parts of the application.

The ShoppingCart class has three methods - addItem(), removeItem(), and getItems(). These methods perform basic operations on a shopping cart.

The addItem() method takes an argument item and adds it to the shopping cart by pushing it to an array called items. After adding the item to the cart, the method emits an "itemAdded" event with the item as its argument. This event can be listened to by other parts of the application that may want to perform some action when an item is added to the cart.

The removeItem() method takes an argument item and removes it from the shopping cart if it exists in the items array. If the item is successfully removed, the method emits an "itemRemoved" event with the item as its argument. If the item is not found in the cart, a message is logged to the console to indicate that the item is not available in the cart.

The getItems() method returns an array of items in the shopping cart. If the cart is empty, a message is logged to the console to indicate that there are no items in the cart.

After defining the ShoppingCart class, an instance of the class named cart is created. Two event listeners are then registered on the cart instance using the on() method. The first event listener listens for the "itemAdded" event and logs a message to the console when an item is added to the cart. The second event listener listens for the "itemRemoved" event and logs a message to the console when an item is removed from the cart.

Finally, the cart.addItem() method is called twice with the arguments "Apple" and "Banana", respectively. When an item is added to the cart, the "itemAdded" event is emitted and the first event listener logs a message to the console. When an item is removed from the cart, the "itemRemoved" event is emitted and the second event listener logs a message to the console. The cart.getItems() method is called to retrieve the list of items in the cart. If the cart is not empty, the list of items is returned. If the cart is empty, a message is logged to the console to indicate that there are no items in the cart.

Did you find this article valuable?

Support Elias Soykat by becoming a sponsor. Any amount is appreciated!