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('data事件执行了'); }); myEmitterIns.on('data1',(data1)=>{ console.log("data1事件开始执行..."); }); myEmitterIns.emit('data',{a:1}); myEmitterIns.emit('data1',{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('data',function(data){ setImmediate(()=>{ console.log('data事件执行了...'); }); });
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('one',(data)=>{ console.log(data); }); myEmitterIns.emit('one','this is first call!'); myEmitterIns.emit('one','this is second call!');
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('data',function(e){ console.log(e); }); myEmitterIns.removeListener('data',function(e){ console.log(e); }); myEmitterIns.emit('data','hello data!'); function deal(e){ console.log(e); } myEmitterIns.on('data1',deal); myEmitterIns.removeListener('data1',deal); myEmitterIns.emit('data1','hello data1!');
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('data事件执行了...A'); } myEmitterIns.on('data',function(e){ console.log(e); myEmitterIns.removeListener('data',dealData1);//这里解除dealData1的绑定 }); myEmitterIns.on('data',dealData1); myEmitterIns.emit('data','data事件执行了...B'); /*执行结果为: data事件执行了...B data事件执行了...A */ //再次触发该事件时,dealData1回调已经被解除绑定了 myEmitterIns.emit('data','data事件执行了...'); //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('data',cbA); emitter.on('data',cbB); console.log('emitter实例的data事件绑定了%d个回调函数',emitter.listenerCount('data')); console.log('它们是:',emitter.listeners('data'));
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('data',cbA); emitter.on('data',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.

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
