跟踪事件循环上的医生,
考虑下面的片段,
const fs = require('fs');
const http = require('http');
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
http.createServer(function (req, res) {
res.write('Hello World!');
console.log("Response sent");
res.end();
}).listen(8081);
setInterval(() => console.log("Timeout callback"), 1000)现在,由于nodejs是事件驱动的,所以我假设nodejs下的内容将触发特定于节点的事件。
问题1:我的假设正确吗?
现在,当有一个传入的HTTP请求到nodejs时,函数代码和相关变量驻留在eventloop循环之外。这意味着应该有数据结构来弥补这一差距。
问题2:nodejs中遇到的事件如何在特定阶段执行回调函数?
发布于 2020-03-06 08:06:54
也许,我理解偶数循环工作原理的方法与您不同,但我展示了基于您的代码的理解(为了便于解释,我添加了一些更同步的代码行)。
const fs = require('fs');
const http = require('http');
// Every time Nodejs faces a block of synchronous code, it will push this function into a call-stack (the execution stack like other programming language)
console.log('run 1');
// Everty time NodeJS faces a block of asynchronous code, it will pass its jobs and its callback function to a lib called libuv to handle.
// when libuv finishs its job (asynchronous operation), it will push the callback function into a queue called event-queue
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
// Another synchronous code
console.log('run 2');
// Another asynchronous code
http.createServer(function (req, res) {
res.write('Hello World!');
console.log("Response sent");
res.end();
}).listen(8081);在所有这些注释之后,您可以想象我们有一个堆栈和一个队列。事件循环的重复工作是
步骤1:查看堆栈(调用堆栈),如果里面有函数,执行它直到堆栈为空。
步骤2:查看队列(事件队列),如果里面有任何函数,执行它直到队列为空。
步骤3:重复步骤1。
P/S:为了获得更多的细节和可视化,这个视频是描述事件循环工作方式的最好来源。希望能帮上忙
https://stackoverflow.com/questions/60559584
复制相似问题