Let's talk about the event loop in Node
The event loop is a fundamental part of Node.js. It 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!
You've been using Node.js for a while, built a few apps, tried out different modules, and even feel comfortable with asynchronous programming. But something keeps bothering you - the event loop.
If you are like me, you have spent countless hours reading documentation and watching videos trying to understand the event loop. But even as an experienced developer, you may have trouble fully understanding how it works. That’s why I’ve prepared this visual guide to help you fully understand the Node.js event loop. So sit back, grab a cup of coffee, and let’s dive into the world of the Node.js event loop. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
Asynchronous programming in JavaScript
We will start from A review of asynchronous programming in JavaScript begins. While JavaScript is used in web, mobile, and desktop applications, it's important to remember that, at its core, JavaScript is a synchronous, blocking, single-threaded language. Let us understand this sentence through a short code snippet.
// index.js function A() { console.log("A"); } function B() { console.log("B"); } A() B() // Logs A and then B
JavaScript is synchronous
If we have two functions that log messages to the console, then the code will be executed from top to bottom, only executing each time One line. In the above code snippet, we see that A is recorded before B.
JavaScript is blocking
JavaScript is blocking due to its synchronous nature. No matter how long the previous process takes, subsequent processes will not start until the former completes. In the code snippet, if function A has to execute a large block of code, JavaScript has to complete that operation without branching to function B. Even if this piece of code takes 10 seconds or even a minute.
You may have encountered this situation in your browser. When a web application is running in the browser and executes some intensive blocks of code without returning control to the browser, the browser may freeze, which is called blocking. The browser is blocked from continuing to process user input and perform other tasks until the web application returns processor control to the browser.
JavaScript is single-threaded
A thread is the process that your JavaScript program can use to run tasks. Each thread can only perform one task at a time. Unlike other languages that support multi-threading and can run multiple tasks simultaneously, JavaScript has only one thread called the main thread that executes code.
Waiting for JavaScript
As you can imagine, this JavaScript model creates problems because we have to wait for the data to be fetched before we can continue executing the code. This wait may take several seconds, during which we cannot run any other code. If JavaScript continues processing without waiting, an error occurs. We need to implement asynchronous behavior in JavaScript. Let's go into Node.js and take a look.
Node.js Runtime
The Node.js runtime is an environment that you can use without using a browser Use and run JavaScript programs. Core - the Node runtime, consists of three main components.
- External dependencies — such as V8, libuv, crypto, etc. — are required features of Node.js
- C features provide functionality such as file system access and networking.
- The JavaScript library provides functions and tools to facilitate calling C features using JavaScript code.
While all parts are important, the key component of asynchronous programming in Node.js is libuv.
Libuv
Libuv is a cross-platform open source library written in C language. In the Node.js runtime, its role is to provide support for handling asynchronous operations. Let's take a look at how it works.
Code execution in Node.js runtime
让我们来概括一下代码在 Node 运行时中的执行方式。在执行代码时,位于图片左侧的 V8 引擎负责 JavaScript 代码的执行。该引擎包含一个内存堆(Memory heap)和一个调用栈(Call stack)。
每当声明变量或函数时,都会在堆上分配内存。执行代码时,函数就会被推入调用栈中。当函数返回时,它就从调用栈中弹出了。这是对栈数据结构的简单实现,最后添加的项是第一个被移除。在图片右侧,是负责处理异步方法的 libuv。
每当我们执行异步方法时,libuv 接管任务的执行。然后使用操作系统本地异步机制运行任务。如果本地机制不可用或不足,则利用其线程池来运行任务,并确保主线程不被阻塞。
同步代码执行
首先,让我们来看一下同步代码执行。以下代码由三个控制台日志语句组成,依次记录“First”,“Second”和“Third”。我们按照运行时执行顺序来查看代码。
// index.js console.log("First"); console.log("Second"); console.log("Third");
以下是 Node 运行时执行同步代码的可视化展示。
执行的主线程始终从全局作用域开始。全局函数(如果我们可以这样称呼它)被推入堆栈中。然后,在第 1 行,我们有一个控制台日志语句。这个函数被推入堆栈中。假设这个发生在 1 毫秒时,“First” 被记录在控制台上。然后,这个函数从堆栈中弹出。
执行到第 2 行时。假设到第 2 毫秒了,log 函数再次被推入堆栈中。“Second”被记录在控制台上,并弹出该函数。
最后,执行到第 3 行了。第 3 毫秒时,log 函数被推入堆栈,“Third”将记录在控制台上,并弹出该函数。此时已经没有代码要执行,全局也被弹出。
异步代码执行
接下来,让我们看一下异步代码执行。有以下代码片段:包含三个日志语句,但这次第二个日志语句传递给了fs.readFile()
作为回调函数。
执行的主线程始终从全局作用域开始。全局函数被推入堆栈。然后执行到第 1 行,在第 1 毫秒时,“First”被记录在控制台中,并弹出该函数。然后执行移动到第 2 行,在第 2毫秒时,readFile
方法被推入堆栈。由于 readFile
是异步操作,因此它会转移(off-loaded)到 libuv。
JavaScript 从调用堆栈中弹出了 readFile
方法,因为就第 2 行的执行而言,它的工作已经完成了。在后台,libuv 开始在单独的线程上读取文件内容。在第 3 毫秒时,JavaScript 继续进行到第 5 行,将 log 函数推入堆栈,“Third”被记录到控制台中,并将该函数弹出堆栈。
大约在第 4 毫秒左右,假设文件读取任务已经完成,则相关回调函数现在会在调用栈上执行, 在回调函数内部遇到 log 函数。
log 函数推入到到调用栈,“Second”被记录到控制台并弹出 log 函数 。由于回调函数中没有更多要执行的语句,因此也被弹出 。没有更多代码可运行了 ,所以全局函数也从堆栈中删除 。
控制台输出“First”,“Third”,然后是“Second”。
Libuv 和异步操作
很明显,libuv 用于处理 Node.js 中的异步操作。对于像处理网络请求这样的异步操作,libuv 依赖于操作系统原生机制。对于没有本地 OS 支持的异步读取文件的操作,libuv 则依赖其线程池以确保主线程不被阻塞。然而,这也引发了一些问题。
- 当一个异步任务在 libuv 中完成时,什么时候 Node 会在调用栈上运行相关联的回调函数?
- Node 是否会等待调用栈为空后再运行回调函数?还是打断正常执行流来运行回调函数?
- 像
setTimeout
和setInterval
这类延迟执行回调函数的方法又是何时执行回调函数呢? - 如果
setTimeout
和readFile
这类异步任务同时完成,Node 如何决定哪个回调函数先在调用栈上运行?其中一个会有更多的优先级吗?
所有这些问题都可以通过理解 libuv 核心部分——事件循环来得到答案。
What is the event loop?
Technically speaking, the event loop is just a C language program. But in Node.js, you can think of it as a design pattern for coordinating the execution of synchronous and asynchronous code.
Visualizing the event loop
The event loop is a loop that runs as long as your Node.js application is running. There are six different queues in each loop, each containing one or more callback functions that need to eventually be executed on the call stack.
- First, there is a timer queue (timer queue. Technically called min-heap), which saves the same number as
setTimeout
Callback functions related tosetInterval
. - Secondly, there is an I/O queue (I/O queue), which contains callback functions related to all asynchronous methods, such as
fs
andhttp
modules related methods provided. - The third one is the check queue, which holds the callback function related to the
setImmediate
function, which is a Node-specific function. - The fourth is the close queue (close queue), which saves the callback function associated with the asynchronous task closing event.
Finally, there are two different queues forming the microtask queue.
- nextTick queue stores the callback function associated with the
process.nextTick
function. - The Promise queue stores the callback functions associated with local
Promise
in JavaScript.
It should be noted that timers, I/O, check and close queues all belong to libuv. However, the two microtask queues do not belong to libuv. Nonetheless, they still play an important role in the Node runtime environment and play an important role in the order in which callbacks are executed. Having said that, let’s understand how the event loop works.
How does the event loop work?
The arrow in the picture is a hint, but it may not be easy to understand. Let me explain the queue priority order. The first thing to know is that all user-written synchronous JavaScript code takes precedence over asynchronous code. This means that the event loop only functions when the call stack is empty.
In the event loop, the order of execution follows certain rules. There are still some rules that need to be mastered. Let’s take a look at them one by one:
- Execute all callback functions in the microtask queue. First the tasks in the nextTick queue, then the tasks in the Promise queue.
- Execute all callback functions in the timer queue.
- If there is a callback function in the microtask queue, all callback functions in the microtask queue will be executed after each callback function is executed in the timer queue. First the tasks in the nextTick queue, then the tasks in the Promise queue.
- Execute all callback functions in the I/O queue.
- If there are callback functions in the microtask queue, all callback functions in the microtask queue will be executed sequentially in the order of nextTick queue and then Promise queue.
- Execute all callback functions in the check queue.
- If there is a callback function in the microtask queue, all callback functions in the microtask queue will be executed after checking each callback in the queue. First the tasks in the nextTick queue, then the tasks in the Promise queue.
- Execute all callback functions in the close queue.
- At the end of the same loop, execute the microtask queue again. First the tasks in the nextTick queue, then the tasks in the Promise queue.
At this time, if there are more callbacks to be processed, the event loop runs again (Annotation: The event loop keeps running while the program is running, and there are currently no tasks to process. Next, it will be in a waiting state and will be executed as soon as there is a new task), and repeat the same steps. On the other hand, if all callbacks have been executed and there is no more code to process, the event loop exits.
This is what the libuv event loop does for executing asynchronous code in Node.js. With these rules in hand, we can revisit the questions we asked earlier.
When an asynchronous task completes in libuv, when will Node run the associated callback function on the call stack?
Answer: The callback function is only executed when the call stack is empty.
Will Node wait for the call stack to be empty before running the callback function? Or interrupt the normal execution flow to run the callback function?
Answer: Running the callback function will not interrupt the normal execution flow.
Methods like setTimeout
and setInterval
that delay the execution of callback functions, when do they execute the callback function?
Answer: The first priority among all callback functions of setTimeout
and setInterval
is executed (regardless of the microtask queue).
If two asynchronous tasks (such as setTimeout
and readFile
) complete at the same time, how does Node decide which callback function to execute first in the call stack? ? Will one have higher priority than the other?
Answer: In the case of simultaneous completion, the timer callback will be executed before the I/O callback.
We have learned a lot so far, but I hope you can keep the execution sequence shown in the picture below in mind, because it completely shows what Node.js does behind the scenes. How to execute asynchronous code.
But, you may ask: "Where is the code to verify this visualization?". Well, each queue in the event loop has implementation nuances, so we'd better talk about them one by one. This article is the first in a series about the Node.js event loop. Please be sure to check the link at the end of the article to understand the details of the operation in each queue. Even if you have a deep impression in your mind now, you may still fall into some traps when you get to the specific scenario.
Conclusion
This visual guide covers the basics of asynchronous programming in JavaScript, the Node.js runtime, and libuv, which is responsible for handling asynchronous operations. With this knowledge, you can build a powerful event loop model that will benefit when writing code that takes advantage of the asynchronous nature of Node.js.
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of Let's talk about the event loop in Node. 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

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

What is front-end ESM? Specific code examples are required. In front-end development, ESM refers to ECMAScriptModules, a modular development method based on the ECMAScript specification. ESM brings many benefits, such as better code organization, isolation between modules, and reusability. This article will introduce the basic concepts and usage of ESM and provide some specific code examples. The basic concept of ESM In ESM, we can divide the code into multiple modules, and each module exposes some interfaces for other modules to

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces
