Things to know about event-driven programming in Node.js

Node's powerful event-driven architecture is one of its strongest advantages. Here's everything you need to know about event-driven programming in Node.js.

Things to know about event-driven programming in Node.js Picture 1Things to know about event-driven programming in Node.js Picture 1

When building any software application, an important decision involves choosing the right model for your code.

Object-oriented programming is a good choice for interactive applications that respond to user actions that can occur in any order. It is a more common pattern with GUI apps than with command line programs or embedded system code.

What is an event or event?

You can think of an event as an action or number of occurrences that code can recognize and respond to. The system or a user can trigger the event and the code will always register a function to handle it.

A basic event example is a button click that performs a specific action. The button click action runs an event, and the function that runs when the click occurs is an event listener or handler.

What is event-driven programming?

Event-driven programming is a programming model in which app execution depends on events occurring, rather than following a strict sequence.

 

This model is mainly used when building user interfaces and apps in real time, where an event such as a user action triggers a task in the system.

This pattern is very common when building web apps, where event listeners run when the user interacts with the Document Object Model (DOM).

The following image illustrates how event-driven programming flows. When an event happens, the event channel receives it and passes it on to the appropriate event listener for processing:

Things to know about event-driven programming in Node.js Picture 2Things to know about event-driven programming in Node.js Picture 2

Event-driven programming in Node.js

JavaScript event looping is a fundamental concept behind the asynchronous nature of the Node.js runtime. An event-driven architecture uses the built-in EventEmitter module to facilitate a seamless execution flow.

With event-driven programming, Node.js allows you to create server-side applications that can handle user interactions, I/O operations, and data processing in real time. This happens in a non-blocking manner, aiming for enhanced performance and a smoother experience for users.

Implementing event-driven programming in Node.js is easy once you understand the basics of defining, triggering, and handling events.

Class EventEmitter

With the EventEmitter class in Node.js, you can create custom events and attach event listeners to handle them. To use this class in code, import it from the events module as follows:

// CommonJS const { EventEmitter } = require("events") // ES6 import { EventEmitter } from "events"

 

This class and its member functions will then be available for you to use in your app. To start running and processing events, instantiate a new instance of the EventEmitter class .

For example:

const FoodEvents = new EventEmitter()

This creates a new player object called FoodEvents , which can run events and register listeners. The EventEmmitter class provides three methods for listening to an event: on , addListener , and once .

The on method is the most basic function for adding an event listener, and addListener works exactly this way. Both accept an event name and a callback function as arguments. Callback is actually a handler function. You can use on and addListener interchangeably.

Here's how you handle events using the on method :

FoodEvents.on("cookie_ready", (data) => { console.log("Cookie ready for packaging, data received: ", data); })

Use addListener as a direct alternative to on :

FoodEvents.addListener("cookie_ready", (data) => { console.log( "Cookie will now be packaged and sent out, data received: ", data ); })

Both of these examples will add a callback to the array of event listeners for the cookie_ready event . If you use both, their callbacks will run in order .

The once method fires the event listener once, running the next event. The system then removes it from the event listener's array.

Here's how to use once to handle a one-time event:

FoodEvents.once("cookie_sent", (data) => { console.log("Cookie is sent out, data received: ", data); })

In this case, the emitter will only listen to the cookie_sent event once and remove the handler after it runs.

Don't forget that, for a listener to handle an event, the application must dispose of the event at some point. Here is some sample code to run the cookie_ready event using the emit method :

function bakeCookie() { console.log("Cookie is baking, almost ready.") setTimeout(() => { FoodEvents.emit("cookie_ready", { flavor: "vanilla cookie" }) }, 3000) } bakeCookie()

When you run the code that prints the message in the console that the cookie is being 'processed', wait 3 seconds and run the cookie_ready event , you will get the result as shown below:

Things to know about event-driven programming in Node.js Picture 3Things to know about event-driven programming in Node.js Picture 3

This represents how event listeners run in the order you register them.

The EventEmitter class provides more methods, including:

 

  1. removeListener : Removes an event listener instance from the event listener array. The off method is also available for this purpose.
  2. prependListener : This method also registers an event listener but, instead of adding it to the end of the event listener array, it is added to the start. It will then run before any other event listeners you may have registered.
  3. prependOnceListener : It works like prependListener, but the event listener runs only once, as in the case of once.
  4. removeAllListeners : This function removes all event listeners registered for a specifically named event, or all event listeners if you pass no arguments to it.
  5. Listeners : Returns an array of event listeners of the event names you pass to it as arguments.
  6. eventNames : You can use this function to get the entire event name registered to an event listener.
  7. setMaxListeners : Node.js defaults to playing an alert when you register more than 10 listeners for an event, to prevent memory leaks. You can adjust this default value using setMaxListeners. You can also check this value using getMaxListeners.

The events package provides comprehensive functionality for event-driven programming in Node.js.

Some of the best object-oriented programming methods

  1. Use accurately descriptive names for events to enable a clean and maintainable codebase.
  2. Apply good error handling and logging, to enable easy debugging.
  3. Avoid nesting multiple callbacks when writing event listeners. Instead, use JavaScript promises.
  4. Don't create too many event listeners for one event. Instead, consider separating events and chaining them.

Above are the things you need to know about event-driven programming in Node.js. Hope the article is useful to you.

5 ★ | 1 Vote