In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains how to use the events module in Node.js. Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn how to use the events module in Node.js.
Most of Node.js's core APIs are built around the idiomatic asynchronous event-driven architecture, in which certain types of objects (called "triggers") trigger named events that cause Function objects ("listeners") to be invoked.
Through the study and application of Node, we know that NodeJS adopts single-threaded, event-driven, non-blocking I/O architecture design, which is very suitable for high-concurrency, I/O-intensive applications.
1. What is event-driven?
Event-driven, simply speaking, is to monitor the change of event state through effective methods, and make corresponding actions when changes occur.
Take a life application scenario to understand: when we go to a restaurant to order food, when we place an order, the waiter tells us the order number (which can be understood as registering an event at this time), we sit and wait, at this time our ears have been listening to the waiter shouting number, when we call, we can go to the front desk to pick up the meal.
2. event model
NodeJS 'event architecture follows the classic subscription publishing pattern
Subscribe to publish pattern, also can be called message mechanism, defines a kind of dependency relationship, this kind of dependency relationship can be understood as 1 to N(multiple or single) observers listen to the corresponding state transition of an object at the same time, once the change is notified to all observers, thus triggering the corresponding event registered by observers, this design pattern solves the coupling between the function of the subject object and the observer.
3. events module
The events module is a very important module in NodeJS. Most of the module implementations in node inherit the Events class, such as fs,http,net, etc. It provides an object events.EventEmitter, the core of EventEmitter is event emitter and event listener.
Simple use:
import { EventEmitter } from 'events';class MyEmitter extends EventEmitter{};const myEmitter = new MyEmitter ();myEmitter.on('hello', () => { console.log('hello someone calls you ');});myEmitter.emit('hello');4. Events Module Core API
4.1 eventEmitter.on(eventName, callback)
Register for listening events
Parameters:
eventName: Event Name
callback: event triggers callback function called
4.2 eventEmitter.once(eventName, callback)
You can register a listener that is invoked at most once for a particular event. Once the event is triggered, the listener is logged off and invoked.
Parameters:
eventName: Event Name
callback: event triggers callback function called
4.3 eventEmitter.emit(eventName[, ... args])
Trigger specified listening events
Parameters:
eventName: Event Name
args Optional parameters, passed in the callback function parameters in order;
4.4 eventEmitter.removeListener(eventName, callback)
Remove the listener for the specified event. Note: The listener must be registered. Otherwise, it's invalid.
Parameters:
eventName: Event Name
callback: callback
4.5 EventEmitter.removeAllListeners(eventName)
Remove all listeners. An event can have multiple listeners. This method can be used when all listeners need to be removed.
Parameters:
eventName: name of event to be removed;
Special attention should be paid to the fact that if no parameters are passed, all monitoring events will be removed, which is more violent and recommended to be used with caution.
4.6 EventEmitter.listeners(eventName)
Returns a copy of the Lister-bound callback function array for an event named eventName.
4.7 EventEmitter.eventNames()
Returns an array listing the events for which triggers have registered listeners.
4.8 EventEmitter.setMaxListeners(n)
By default, EventEmitter prints a warning if more than 10 listeners are added for a particular event.
The emitter.setMaxListeners() method allows you to modify the limits of this particular EventEmitter instance. This value can be set to Infinity (or 0) to indicate an infinite number of listeners.
5. synchronous asynchronous problem
EventEmitter calls all listeners synchronously in the order they are registered. This ensures proper sequencing of events and helps avoid race conditions and logical errors.
6. error handling
When an error occurs in an EventEmitter instance, the typical action is to trigger an 'error' event. These are considered special cases in Node.js.
If EventEmitter does not register at least one listener for an 'error' event and fires an 'error' event, it throws an error, prints a stack trace, and exits the Node.js process.
As a best practice, always add a listener for the 'error' event.
import { EventEmitter } from 'events';class MyEmiter extends EventEmitter{};const myEmitter = new MyEmiter();myEmitter.on ('hello', () => { console.log ('hello someone called you');});myEmitter.on ('error', (e) => { console.log(e)})myEmitter.emit('hello'); myEmitter.emit ('error ', new Error ('an error happen')) At this point, I believe that everyone has a deeper understanding of "how to use the events module in Node.js", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.