An article to talk about the event-loop mechanism in Node.js
This article will take you to understand the event-loop (time loop) mechanism in Node.js. I hope it will be helpful to you!
Today we will learn about event-loop in nodeJs. The understanding of event-loop has always been a big difficulty for me. I hope to break through this difficulty through this study. I also hope to deepen my understanding and impression of event-loop through this blog.
libuv
Before learning event-loop, first understand the libuv of node. libuv is responsible for the implementation of different I/O models on different operating systems, and abstracts different implementations into APIs that can be used with third-party applications.
Question
Before formally learning event-loop, let’s think about a question
setTimeout(() => { console.log("timer1"); Promise.resolve().then(() => { console.log("promise1"); }); }, 0); setTimeout(() => { console.log("timer2"); Promise.resolve().then(() => { console.log("promise2"); }); }, 0);
This code What is the result of running it in the browser?
What is the result of running it in node?
Before node8.6:
##After node8.6:
event-loop in nodeJs
First of all, Let’s look at a picture:- timers phase: mainly execute setTimeOut, setInterval callbacks
- pending callbacks phase: execute some system call errors, such as network communication Error callback
- idle/prepare phase: only used within the system (we cannot control and interfere with this phase)
- poll phase: get new I/O events, such as getting an I/O callback for reading a file.
Under appropriate circumstances, nodejs will block in this phase
- check phase: execute setImmediate callback
- For example Execute the destroy and close event callbacks of sokect
FIFO(First in first out) rule to execute the task queue tasks inside. Among these six stages, we focus on the timers, poll, check stages. Most of the asynchronous tasks in our daily development are handled in these three stages.
timers
Let’s talk about the timers stage first.
Timers is the first stage of the event loop. Nodejs will check whether there is an expired timer, and if so, put its callback into the queue. However, nodejs cannot guarantee that the timer will execute the callback immediately when the preset event arrives. This is because the expiration check of the timer by nodejs is not necessarily reliable. It will be affected by other running programs on the machine, or it will encounter the current main thread. Not idle situation. Regarding the uncertainty here, the official website gives an example:
First declare a setTimeOut, and then read a file externally. When the file reading operation exceeds the timer time, in this way, the read File operations will delay the timer's callback. This is the situation where the main thread is not idle as mentioned earlier.
poll
The poll phase mainly performs two things: 1. Process the task queue of the poll phase 2. When there is a timer that has timed out, its callback function is executedAfter executing the poll task queue in the poll phase After the task, it will check whether there is a preset setImmediate. If there is, it will enter the check phase. If not, nodejs will block here.
Here we will have a question. If it is blocked in the poll stage, wouldn't the timer we set cannot be executed?In fact
When the event-loop is blocked in the poll phase, nodejs will have a checking mechanism. It will check whether the timers queue is empty. If it is not empty, it will re-enter the timers phase.
check
The check phase mainly executes the setImmediate callback function.小总结
event-loop的每个阶段都有一个队列,当event-loop达到某个阶段之后,将执行这个阶段的任务队列,直到队列清空或者达到系统规定的最大回调限制之后,才会进入下一个阶段。当所有阶段都执行完成一次之后,称event-loop完成一个tick。
案例
上面我们说完了event-loop的理论部分,但是光有理论我们也还是不能很清晰的理解event-loop。下面我们就根据几个demo来更加深入的理解下event-loop!
demo1
const fs=require('fs') fs.readFile('test.txt',()=>{ console.log('readFile') setTimeout(()=>{ console.log('settimeout'); },0) setImmediate(()=>{ console.log('setImmediate') }) })
执行结果:
可见执行结果跟我们前面的分析时一致的!
demo2
const fs = require("fs"); const EventEmitter = require("events").EventEmitter; let pos = 0; const messenger = new EventEmitter(); messenger.on("message", function (msg) { console.log(++pos + " message:" + msg); // }); console.log(++pos + " first"); // process.nextTick(function () { console.log(++pos + " nextTick"); // }); messenger.emit("message", "hello!"); fs.stat(__filename, function () { console.log(++pos + " stat"); // }); setTimeout(function () { console.log(++pos + " quick timer"); // }, 0); setTimeout(function () { console.log(++pos + " long timer"); // }, 30); setImmediate(function () { console.log(++pos + " immediate"); // }); console.log(++pos + " last"); //
结果:
了解下浏览器和node的event-loop差异在什么地方
在node 8.6 之前:
浏览器中的微任务队列会在每个宏任务执行完成之后执行,而node中的微任务会在事件循环的各个阶段之间执行,即每个阶段执行完成之后会去执行微任务队列。
在8.6之后:
浏览器和node中微任务的执行是一致的!
所以,在文章开头,我们提出的思考的问题就有了结果。
关于 process.nextTick()和setImmediate
process.nextTick()
语法:process.nextTick(callback,agrs)
执行时机:
这个函数其实是独立于 Event Loop 之外的,它有一个自己的队列,当每个阶段完成后,如果存在 nextTick 队列,就会清空队列中的所有回调函数,并且优先于其他 microtask 执行。递归的调用process.nextTick()
会导致I/O starving,官方推荐使用setImmediate()
关于starving现象的说明:
const fs = require("fs"); fs.readFile("test.txt", (err, msg) => { console.log("readFile"); }); let index = 0; function handler() { if (index >= 30) return; index++; console.log("nextTick" + index); process.nextTick(handler); } handler();
运行结果:
可以看到,等到nextTick函数呗执行30次之后,读取文件的回调才被执行!这样的现象被称为 I/O 饥饿。
当我们把 process.nextTick 换为 setImmediate
const fs = require("fs"); fs.readFile("test.txt", (err, msg) => { console.log("readFile"); }); let index = 0; function handler() { if (index >= 30) return; index++; console.log("nextTick" + index); setImmediate(handler); } handler();
结果:
造成这两种差异的原因是,嵌套调用的setImmediate的回调被排到了下一次event-loop中去!
event-loop核心思维导图
结束语
通过今天的学习,让我对event-loop的理解更深刻了。那么,下次见。好好学习,天天向上!
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of An article to talk about the event-loop mechanism 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

AI Hentai Generator
Generate AI Hentai for free.

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



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

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!

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.

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 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!

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

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!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".
