Home Web Front-end JS Tutorial Detailed explanation of Node.js: events event module

Detailed explanation of Node.js: events event module

Dec 05, 2016 pm 01:37 PM
node.js

Most of the core APIs of Nodejs are designed based on asynchronous event-driven design, and all objects that can distribute events are instances of the EventEmitter class.

As we all know, since nodejs runs in a single thread, nodejs needs to use event polling to continuously query event messages in the event queue, and then execute the callback function corresponding to the event, which is somewhat similar to the message mapping mechanism of windows. As for the more detailed implementation links, you can find information separately.

The following introduces the use of EventEmitter.

1. Listening for events and distributing events

EventEmitter instances can use on or addListener to listen for events and the emit() method to distribute events, as shown below:

const events = require('events'),
   EventEmitter = events.EventEmitter,
   util = require('util');
function myEmiter(){
  EventEmitter.call(this);
};
util.inherits(myEmiter,EventEmitter);//继承EventEmitter类
const myEmitterIns = new myEmiter();
myEmitterIns.on('data',(o)=>{
  console.log('receive the data:'+o.a);
});
Copy after login

or use the class class

class myEmiter extends EventEmitter{}//继承EventEmitter类
const myEmitterIns = new myEmiter();
 
myEmitterIns.on('data',(o)=>{
  console.log('receive the data:'+o.a);
});
myEmitterIns.emit('data',{a:1});
Copy after login

The execution results are as follows:

E:developmentdocumentnodejsdemo>node event-example.js
receive the data:1

2. Pass parameters to the event listening callback function

As can be seen from the above example, the emit() method can Pass any set of parameters to the callback function. One thing to note is that the this keyword points to the EventEmiter instance that calls the emit method, except in the arrow function. This points to the global this, because this in the arrow function is defined time binding. As shown below:

class myEmiter extends EventEmitter{}
const myEmitterIns = new myEmiter();
myEmitterIns.on('data',function(data){
  console.log("普通回调函数中this:");
  console.log(this);
});
myEmitterIns.on('data1',(data1)=>{
  console.log("箭头回调函数中this:");
  console.log(this);
});
myEmitterIns.emit('data',{a:1});
myEmitterIns.emit('data1',{a:1});
Copy after login

The execution result is as follows:

E:developmentdocumentnodejsdemo>node event-example.js
This in the ordinary callback function:
myEmiter {
domain: null,
_events: { data: [Function ], data1: [Function] },
_eventsCount: 2,
_maxListeners: undefined }
this in the arrow callback function:
{}

Here we talk about this in the arrow function. By the way, why the arrow function can be implemented Binding this when defining is because there is no mechanism to bind this inside the arrow function. It uses this in the outer scope, so it cannot be used as a constructor.

3. Execution sequence of event listener

EventEmiter instance can bind multiple events. When we trigger these events sequentially, EventEmiter will execute in synchronous mode. Even if the first event processing function is not completed, it will not Trigger the next event as follows:

class myEmiter extends EventEmitter{}
const myEmitterIns = new myEmiter();
myEmitterIns.on('data',function(data){
  console.time('data事件执行了');
  for(var i = 0 ; i< 100000; i++)
    for(var j = 0 ; j< 100000; j++)
      ;
  console.timeEnd(&#39;data事件执行了&#39;);
});
myEmitterIns.on(&#39;data1&#39;,(data1)=>{
  console.log("data1事件开始执行...");
});
myEmitterIns.emit(&#39;data&#39;,{a:1});
myEmitterIns.emit(&#39;data1&#39;,{a:1});
Copy after login

The execution result is as follows:

E:developmentdocumentnodejsdemo>node event-example.js
data event executed: 4721.401ms
data1 event started execution...

Of course, we can use asynchronous operations in the callback function, such as setTimeout, setImmediate or process.nextTick(), etc., to achieve asynchronous effects, as shown below:

myEmitterIns.on(&#39;data&#39;,function(data){
  setImmediate(()=>{
    console.log(&#39;data事件执行了...&#39;);
  });
});
Copy after login

The execution results are as follows:

E:developmentdocumentnodejsdemo> node event-example.js
data1 event was executed...
data event was executed...

4. One-time event monitoring

EventEmiter can use once to listen to an event, then the event handler will only trigger Once, the event will be ignored after emit because the listener is logged out, as shown below:

myEmitterIns.once(&#39;one&#39;,(data)=>{
  console.log(data);
});
myEmitterIns.emit(&#39;one&#39;,&#39;this is first call!&#39;);
myEmitterIns.emit(&#39;one&#39;,&#39;this is second call!&#39;);
Copy after login

The execution results are as follows:

E:developmentdocumentnodejsdemo>node event-example.js
this is first call!

From the above results, it can be seen that the 'one' event is only executed once.

5. Remove event binding

Similar to DOM event listening, EventEmiter can also remove event binding. Use the removeListener(eventName, listener) method to unbind an event, so the callback function listener must be a named function. , otherwise the function cannot be found, because the function is a reference type, even if the function body is the same, it is not the same function, as shown below:

myEmitterIns.on(&#39;data&#39;,function(e){
  console.log(e);
});
myEmitterIns.removeListener(&#39;data&#39;,function(e){
  console.log(e);
});
myEmitterIns.emit(&#39;data&#39;,&#39;hello data!&#39;);
function deal(e){
  console.log(e);
}
myEmitterIns.on(&#39;data1&#39;,deal);
myEmitterIns.removeListener(&#39;data1&#39;,deal);
myEmitterIns.emit(&#39;data1&#39;,&#39;hello data1!&#39;);
Copy after login

The execution result is as follows:

E:developmentdocumentnodejsdemo>node event-example.js
hello data!
E:developmentdocumentnodejsdemo>

As can be seen from the execution results, the data event uses an anonymous function, so it is not removed, while the data1 event is successfully unbound. One thing to note here is that after emit triggers an event, all callback functions bound to the event will be called. Even if you use the removeListener function in a callback function to remove another callback, it will be useless, but subsequent The event queue has removed the callback. As shown below:

function dealData1(e){
  console.log(&#39;data事件执行了...A&#39;);
}
myEmitterIns.on(&#39;data&#39;,function(e){
  console.log(e);
  myEmitterIns.removeListener(&#39;data&#39;,dealData1);//这里解除dealData1的绑定
});
myEmitterIns.on(&#39;data&#39;,dealData1);
myEmitterIns.emit(&#39;data&#39;,&#39;data事件执行了...B&#39;);
/*执行结果为:
 data事件执行了...B
 data事件执行了...A
*/
//再次触发该事件时,dealData1回调已经被解除绑定了
myEmitterIns.emit(&#39;data&#39;,&#39;data事件执行了...&#39;);
//data事件执行了...
   
另外可以使用removeAllListeners()解除所有事件的绑定。
Copy after login

6. Get the number of event listeners and listening functions

Use the emitter.listenerCount(eventName) function to get the number of listeners for a specified event. The function emitter.listeners(eventName) can be used to get all the listeners for a specified event. The listening function is used as follows:

var cbA = ()=>{},
  cbB = ()=>{};
var emitter = new myEmiter();
emitter.on(&#39;data&#39;,cbA);
emitter.on(&#39;data&#39;,cbB);
console.log(&#39;emitter实例的data事件绑定了%d个回调函数&#39;,emitter.listenerCount(&#39;data&#39;));
console.log(&#39;它们是:&#39;,emitter.listeners(&#39;data&#39;));
Copy after login

The execution results are as follows:

E:developmentdocumentnodejsdemo>node event-example.js
The data event of the emitter instance is bound to 2 callback functions
They are: [ [ Function: cbA], [Function: cbB] ]

7. Get and set the maximum number of emitter listeners
nodejs recommends that the number of listeners for the same event should not exceed 10. You can know this by looking at the EventEmitter.defaultMaxListeners property, as follows As shown:

console.log(EventEmitter.defaultMaxListeners);//结果为10个
Copy after login

emitter obtains the maximum number of listeners through the getMaxListeners() method and sets the maximum number of listeners through the setMaxListeners(n) method, as shown below:

var cbA = ()=>{},
  cbB = ()=>{};
var emitter = new myEmiter();
emitter.setMaxListeners(1);
emitter.on(&#39;data&#39;,cbA);
emitter.on(&#39;data&#39;,cbB);
console.log(emitter.getMaxListeners());
Copy after login

The execution results are as follows:

E:developmentdocumentnodejsdemo>node event-example.js
The maximum number of emitter event listeners is: 1
(node:6808) Warning: Possible EventEmitter memory leak detected. 2 data listener
s added. Use emitter .setMaxListeners() to increase limit

As shown in the above results, if the maximum number of listeners is set, it is best not to exceed the maximum number of listeners for the same event, otherwise it is likely to cause a memory leak.


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

Video Face Swap

Video Face Swap

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

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)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

See all articles