NodeJS 事件循环是如何工作的?

How NodeJS event loop works?

对于下面的代码,

var fs = require('fs');

fs.watch('target.txt', function(event, fileName){
    console.log('Event: ' + event + ', for file: ' + fileName);
    });

Console.log('Now watching target.txt');

根据以下架构,

1) fs.watch() 将调用 libuvlibuv 将启动一个线程来跟踪 target.txt 上的 change 事件。来自 libuv 的结果将转到 v8 并以回调的形式再次通过 NodeJS Bindings 并带有包含数据的缓冲区。

2) libuv 在事件队列中添加 change 事件。当事件循环选择 change 事件时,相应的回调将在 v8 运行 时间内执行。

我的理解正确吗?

不对,你误会了。 NodeJS 没有线程,它是单线程的,使用 Observer Pattern. The event loop waits for events to occur (to observe an event). When an event is occurred, then it calls its handler. The illusion of multi-threaded approach comes from the fact that Node frequently uses async events, defining callback functions to be executed when a given task is finished. Read more here.

这篇文章详细解释了事件循环

https://nodesource.com/blog/understanding-the-nodejs-event-loop/

它提供了整个过程的机械概览