search
HomeWeb Front-endJS TutorialDetailed explanation of Node.js: events event module

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);
});

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});

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});

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});

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;);
  });
});

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;);

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;);

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()解除所有事件的绑定。

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;));

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个

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());

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
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.