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

How to use Spark and Scala to analyze Apache access logs

Install First you need to install Java and Scala,...

Detailed explanation of MySQL database isolation level and MVCC

Table of contents 1. Isolation Level READ UNCOMMI...

Use CSS to implement special logos or graphics

1. Introduction Since pictures take up a lot of s...

javascript realizes 10-second countdown for payment

This article shares the specific code of javascri...

JavaScript web page entry-level development detailed explanation

Part 3: ❤Three ways to overlook backend data rece...

Centos7 installation of FFmpeg audio/video tool simple document

ffmpeg is a very powerful audio and video process...

Record the process of connecting to the local Linux virtual machine via SSH

Experimental environment: Physical machine Window...

Solution to MySQLSyntaxErrorException when connecting to MySQL using bitronix

Solution to MySQLSyntaxErrorException when connec...

Docker nginx implements one host to deploy multiple sites

The virtual machine I rented from a certain site ...

mysql startup failure problem and scenario analysis

1. One-stop solution 1. Problem analysis and loca...

JavaScript ES new feature block scope

Table of contents 1. What is block scope? 2. Why ...

How to install and configure the supervisor daemon under centos7

Newbie, record it yourself 1. Install supervisor....

How to implement one-click deployment of nfs in linux

Server Information Management server: m01 172.16....

jQuery achieves the effect of advertisement scrolling up and down

This article shares the specific code of jQuery t...