Table of Contents
events (event trigger)
Home Web Front-end JS Tutorial Let's talk in depth about EventEmitter in node.js

Let's talk in depth about EventEmitter in node.js

May 09, 2022 pm 09:28 PM
nodejs node.js node

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!

Let's talk in depth about EventEmitter in node.js

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触发事件
Copy after login

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);
Copy after login

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') // 不生效了
Copy after login

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,'报错了')
 })
Copy after login

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('报错了'))
Copy after login

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事件
Copy after login

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'); //在这里的时候才是真正被删除掉了
Copy after login

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']
Copy after login

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));
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

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.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

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.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

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.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

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

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

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.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

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.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

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.

See all articles