When building any software application, one crucial decision involves selecting the appropriate paradigm for your code.

Event-driven programming is a good choice for interactive apps that respond to user actions which may occur in any order. It’s a more popular paradigm with GUI apps than with command-line programs or embedded systems code.

visualization of event-driven programming

What Are Events?

You can think of an event as an action or occurrence that your code can recognize and respond to. The system or a user can trigger an event and your code will usually register a function to handle it.

An example of a basic event is clicking a button to perform a particular action. The act of clicking the button fires an event, and the function that runs when the click occurs is called theevent listener(or handler).

console output image

What Is Event-Driven Programming?

Event-driven programming is aprogramming paradigmin which an application’s execution flow depends on events that occur rather than being strictly sequential.

This paradigm is mostly used when building user interfaces and real-time applications, where an event such as a user’s action should trigger an action in the system.

The paradigm is very popular when building web apps, where event listeners trigger when users interact withthe Document Object Model (DOM).

The following image visualizes how the flow works in event-driven programming. When an event occurs, the event channel receives it and passes it on to the appropriate listener to handle:

Event-Driven Programming in Node.js

TheJavaScript event loopis one of the fundamental concepts behind the asynchronous nature of the Node.js runtime. An event-driven architecture uses its built-inEventEmittermodule to facilitate seamless execution flow.

With event-driven programming, Node.js lets you create server-side applications that can handle user interaction, I/O operations, and real-time data processing. This occurs in a non-blocking manner, resulting in enhanced performance and a smoother experience for the user.

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

The EventEmitter Class

With theEventEmitterclass in Node.js, you can create custom events and attach event listeners to handle them. To use the class in your code, import it from theeventsmodule like this:

The class and its member functions are then available for you to use in your application. To start emitting and handling events, initialize a new instance of theEventEmitterclass.

For example:

This creates a new emitter object calledFoodEventsthat can emit events and register listeners. The EventEmmitter class provides three methods for listening to an event:on,addListener,andonce.

Theonmethod is the most basic function for adding event listeners, andaddListenerworks in exactly the same way. They both accept the event name and a callback function as arguments. The callback is the actual handler function. you’re able to useonandaddListenerinterchangeably.

Here’s how you handle an event using theonmethod:

UsingaddListeneras a direct alternative foron:

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

Theoncemethod registers a one-time event listener which runs the next time the event fires. After that, the system will remove it from the array of listeners.

Here’s how to useonceto handle a one-time event:

In this case, the emitter will only listen for thecookie_sentevent once and remove the handler after it has run.

All three methods return the emitter, so you may chain calls to any one of them.

Don’t forget that, for a listener to handle an event, the application must emit that event at some point. Here’s some sample code to emit thecookie_readyevent using theemitmethod:

When you run this code which prints a notice in the console that the cookie is baking, waits for 3 seconds, and emits thecookie_readyevent, you will get an output like the image below:

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

TheEventEmitterclass provides more methods, including:

Theeventspackage provides comprehensive functionality for event-driven programming in Node.js.

What Are Some Event-Driven Programming Best Practices?

Every programming approach has its tradeoffs, and ignoring best practices can have adverse effects on your application. The following are some best practices to consider when building event-driven applications:

Build Applications With the Right Architecture

A general rule that applies to building software is to make appropriate architecture and design decisions. When you follow the wrong approach to building an application, you’ll face the consequences eventually.

Event-driven programming is a paradigm that can have a significant impact on an application’s architecture and performance. Whenever your application, or a part of it, depends on events to function, you should consider event-driven programming.