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
May be interested
- Set of multiple choice questions about programming with P7 prizecurrent programming is no longer strange to us. programming work is becoming hot and more interested. please join the network administrator to learn about programming skills through multiple-choice questions below.
- Set of multiple-choice questions on award-winning programming P5serializing programming tests, in the following article, readers will be able to expand their knowledge with more interesting questions. let's start.
- Set of multiple choice questions about programming with P6the following network administrators will continue to send you interesting questions about programming. if you love this topic, then try your knowledge.
- P13 programming set of multiple choice questionsyou are a fan of programming languages and want to learn more about this topic. to give you an interesting reading about programming, in this article, the network administrator will send you a good quiz about this topic. invite your reference.
- Set of multiple choice questions on programming with P3 prizeinvite readers to participate in testing knowledge with questions around the topic of the following programming of network administrator. the question set will have 10 questions with 4 answers, please choose the most accurate answer.
- Set of multiple choice questions on programming with P16 prizemultiple choice questions about programming will be the first piece of knowledge to help you get started with programming. invite your reference.
- Set of multiple choice questions for programming with P8 prizesfollowing the series of quizzes around programming topics, below invite readers to test their knowledge with multiple choice questions that we have summarized below.
- Set of multiple choice questions on programming with P14 prizeyou are a regular person writing about programming code, so are you confident with your knowledge? try checking with our multiple choice questions below.
- Top 20 free programming learning websites need to bookmark immediately!you will learn lots of useful knowledge from these programming web sites and much more. want to learn programming? want to study programming yourself? so what are you waiting for ...
- How does programming affect our brains?let's tipsmake.com find out how programming affects our brain in the article below!