Let's talk in depth about EventEmitter in node.js
This article will take you to understand the EventEmitter in node, and briefly talk about asynchronous operations, error events, and the EventEmitter class. I hope it will be helpful to everyone!
events (event trigger)
events is the built-in event trigger of nodejs , events are used in many of node's built-in modules. For example, http.server triggers an event every time it receives a request, and stream uses on to listen to corresponding events based on events.
All objects that trigger events are EventEmitter instances. These objects expose EventEmitter.on('event', callback). EventTmitte.on is usually used to register events, and EventEmitter.emit triggers events.
Example:
const events= require('events'); const event=new events();//实例化EventEmitter event.on('data',(a,b)=>{ console.log('参数'+a+b) console.log(this,'this') //注意,如果callback是 箭头函数的话this指向的是全局对象 // 如果callback是function(){}形式的话,this会绑定到EventEmitter实例上 console.log('emit触发了data事件') }) event.emit('data',1,2); //使用emit触发事件
Asynchronous operation
Because EventEmitter.on('event name',callback) The callback in is executed synchronously, but in some cases we have to use asynchronous operations, so we can use SetImmediate to perform asynchronous operations
const events= require('events'); const event=new events(); event.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); //因为这里的监听器是同步执行的,但是我们可以使用setImediate函数等待监听器里的其他内容执行完再执行 }); event.emit('event',1,2);
trigger once
When we normally trigger events through emit, emit will be triggered several times if there are several events, but we can use once to register events, and events triggered using once can only be triggered once
const EventEmitter =require('events'); const MyEventEmitter=new EventEmitter(); let a=0; //正常注册事件和触发 MyEventEmitter.on('add',()=>{ a++ console.log(a) }) MyEventEmitter.emit('add'); // 1; MyEventEmitter.emit('add'); // 2; // 使用once注册 MyEventEmitter.once('add',()=>{ a++ console.log(a); }) MyEventEmitter.emit('add') // 1 MyEventEmitter.emit('add') // 不生效了
error event
EventEmitter does not have an error event, so when an error occurs, it can only be forced to exit execution, so we must register an error event ourselves. So that the error event is triggered when an error occurs
const EventEmitter=require('events'); const MyEventEmitter=new EventEmitter(); MyEvenEmitter.on('error',(err)=>{ console.error(err,'报错了') })
In addition to the above method, we can also use errorMonitor to monitor the error triggered by emit without registering the error event. Using errorMonitor, we no longer need to manually register error events
const {EventEmitter,errorMonitor}=require('events'); const MyEventEmitter=new EventEmitter(); MyEventEmitter.on(errorMonitor,(err)=>{ console.log(err); }) MyEventEmitter('error' , new Error('报错了'))
EventEmitter class
newListener event
The newListener event will be triggered when we add an event listener, so we can register the newListener event to do something when adding an event listener
const {EventEmitter}=require('events'); const MyEvent=new EventEmitter(); MyEvent.on('newListener',(name,litener)=>{ //name就是正在监听的事件的名称 //listener是事件的处理函数 MyEvent.on('event',()=>{ console.log('在newListener添加的事件') }) }) MyEvent.on('event',()=>{ console.log('正常注册的event事件') }) //此时我们再不触发event事件的情况下,newListener事件就会执行,因为我们只要正在注册事件就会触发newListener事件 //注意:newListener事件必须要使用EventEmitter.once()注册,因为如果我们在newListener事件里再去添加注册事件的话,而且外边有多个注册事件就会触发多次newListener事件,就会发生堆栈溢出 MyEvent.emit('event'); //打印的结果 // 在newListener注册的事件 // 正常注册的event事件
removeListener event
The removeListener event is used to delete registered events. However, removeListener will not prevent events that are being triggered by emit.
const callbackB=()=>{ console.log('B') } const callbackA=()=>{ console.log('A') event.removeListener('data',callbackB) } event.on('data',callbackA) event.on('data',callbackB) event.emit('data'); //在执行callbackA的时候删除了data,但是不会阻止掉下一个emit的触发 event.emit('data'); //在这里的时候才是真正被删除掉了
addListener has the same effect as on
eventNames
Returns an array containing the names of all registered events
const {EventEmitter} =require('events'); const MyEvent=new EventEmitter(); MyEvent.on('data',()=>{}); MyEvent.on('finish',()=>{}); console.log(MyEvent.eventNames()); //打印结果 ['data','finish']
getMaxListeners
Returns the maximum number of events that can be registered. The default is 10. If there are more than 10, there will be a warning. But we can modify it through setMaxListener(20)
const {EventEmitter} =require('events'); const MyEvent=new EventEmitter(); console.log(MyEvent.getMaxListener()); //10 event.setMaxListener(20); console.log(MyEvent.getMaxListener(20));
listenerCount
Return the number of registered events
const {EventEmitter} =require('events'); const MyEvent=new EventEmitter(); MyEvent.on('data',()=>{}); MyEvent.on('data',()=>{}); MyEvent.on('finish',()={}); console.log(MyEvent.listenerCount()) // 2
More node related knowledge, Please visit: nodejs tutorial!
The above is the detailed content of Let's talk in depth about EventEmitter in node.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.
