Things to know about event-driven programming in Node.js
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:
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:
This represents how event listeners run in the order you register them.
The EventEmitter class provides more methods, including:
- removeListener : Removes an event listener instance from the event listener array. The off method is also available for this purpose.
- 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.
- prependOnceListener : It works like prependListener, but the event listener runs only once, as in the case of once.
- removeAllListeners : This function removes all event listeners registered for a specifically named event, or all event listeners if you pass no arguments to it.
- Listeners : Returns an array of event listeners of the event names you pass to it as arguments.
- eventNames : You can use this function to get the entire event name registered to an event listener.
- 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
- Use accurately descriptive names for events to enable a clean and maintainable codebase.
- Apply good error handling and logging, to enable easy debugging.
- Avoid nesting multiple callbacks when writing event listeners. Instead, use JavaScript promises.
- 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.
You should read it
- Event Loop in Node.js
- 10 things not to do when running Node.js application
- Schema validation in Node.js using Joi
- Event Emitter in Node.js
- Instructions for installing Node.js
- Concept of Buffer in Node.js
- Read the File record in Node.js
- Utility Module in Node.js
- What is Node.js?
- Set of multiple choice questions about programming with P12
- Beginners of computer programming need to focus on what?
- REPL Terminal in Node.js
Maybe you are interested
This is the culprit that prevents users from updating Windows 11 24H2
Why is the iPhone launch event time always 9:41?
How to watch Apple's iPhone 16 'It's Glowtime' event
Call of Duty prevents hacking by making real gamers invisible
Google recommends turning off 2G signals to prevent fraud
Devices announced by Google at the Made by Google 2024 event