Summary of knowledge points about events module in Node.js

Summary of knowledge points about events module in Node.js

Through the study and application of Node, we know that NodeJS adopts single-threaded, event-driven, non-blocking I/O and other architectural designs, which is very suitable for high-concurrency, I/O-intensive applications.

1. What is event-driven?

Event-driven, in simple terms, is to monitor changes in event status through effective methods and take corresponding actions when changes occur.

Let’s use a scenario from daily life to understand this: when we go to a restaurant to eat and order food, after we place the order, the waiter tells us the order number (this can be understood as registering an event), and we sit and wait. At this time, our ears are always listening to the waiter’s calling number, and when our name is called, we can go to the front desk to pick up the food.

2. Event Model

NodeJS's event architecture uses the classic subscription publishing model

The subscription and publication mode, also known as the message mechanism, defines a dependency relationship, which can be understood as 1 to N (multiple or single) observers simultaneously monitoring the corresponding state changes of an object. Once a change occurs, all observers are notified, thereby triggering the corresponding events registered by the observers. This design pattern solves the functional coupling between the main 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 emission and event listener.

Simple use:

import { EventEmitter } from 'events';
 
class MyEmiter extends EventEmitter{};
 
const myEmitter = new MyEmiter();
 
myEmitter.on('hello', () => {
  console.log('hello someone is calling you');
});
 
myEmitter.emit('hello');

4. Events module core API

4.1 eventEmitter.on(eventName, callback)

Registering Listener Events

parameter:

eventName: event name

callback: callback function called when the event is triggered

4.2 eventEmitter.once(eventName, callback)

It is possible to register a listener which will be called at most once for a specific event. Once the event is triggered, the listener is unregistered and then called.

parameter:

eventName: event name

callback: callback function called when the event is triggered

4.3 eventEmitter.emit(eventName[, ...args])

Trigger the specified listening event

parameter:

eventName: event name

args is an optional parameter, which is passed into the callback function in order;

4.4 eventEmitter.removeListener(eventName, callback)

Remove the listener of the specified event. Note: the listener must be registered. Otherwise it is invalid.

parameter:

eventName: event name

callback: callback function

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.

parameter:

eventName: the name of the event that needs to be removed;

It should be noted that if no parameters are passed, all monitoring events will be removed, which is quite violent and should be used with caution.

4.6 EventEmitter.listeners(eventName)

Returns a copy of the array of listener binding callback functions for the event named eventName.

4.7 EventEmitter.eventNames()

Returns an array listing the events for which the trigger has registered listeners.

4.8 EventEmitter.setMaxListeners(n)

By default, an EventEmitter will print a warning if more than 10 listeners are added for a particular event.

The emitter.setMaxListeners() method allows modifying the limit for this particular EventEmitter instance. This value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

5. Synchronous and asynchronous issues

The EventEmitter calls all listeners synchronously in the order they were registered. This ensures correct ordering of events and helps avoid race conditions and logic errors.

6. Error handling

When an error occurs in an EventEmitter instance, the typical action is to emit an 'error' event. These are treated as special cases in Node.js.

If the EventEmitter does not have at least one listener registered for the 'error' event, and the 'error' event is emitted, the error will be thrown, the stack trace will be printed, and the Node.js process will exit.

As a best practice, you should 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 is calling you');
});
 
myEmitter.on('error', (e) => {
  console.log(e)
})
 
myEmitter.emit('hello');
myEmitter.emit('error', new Error('an error happens'))

This is the end of this article about the knowledge points of the events module in Node.js. For more content related to the events module in Node.js, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of node.JS event mechanism and how to use events module
  • Example analysis of the use of event triggers events in node.js
  • Node.js learning event module Events usage example
  • Introduction to the usage of Node.js events.EventEmitter

<<:  Docker container data volume named mount and anonymous mount issues

>>:  MySQL Learning: Three Paradigms for Beginners

Recommend

Use nginx to configure domain name-based virtual hosts

1. What is a virtual host? Virtual hosts use spec...

How to Check Memory Usage in Linux

When troubleshooting system problems, application...

Details after setting the iframe's src to about:blank

After setting the iframe's src to 'about:b...

js to realize a simple disc clock

This article shares the specific code of js to im...

Detailed analysis of MySQL master-slave replication

Preface: In MySQL, the master-slave architecture ...

vue-cli introduction and installation

Table of contents 1. Introduction 2. Introduction...

Implementation of CSS equal division of parent container (perfect thirds)

The width of the parent container is fixed. In or...

How to regularly clean up docker private server images

Using CI to build docker images for release has g...

A brief discussion on the solution of Tomcat garbled code and port occupation

Tomcat server is a free and open source Web appli...

2017 latest version of windows installation mysql tutorial

1. First, download the latest version of MySQL fr...

Div css naming standards css class naming rules (in line with SEO standards)

There are many tasks to be done in search engine o...

How to draw a mind map in a mini program

Table of contents What is a mind map? How to draw...