蓝色天空.知识 · 实践 · 创造
我的收藏
Node.js 教程目录 38章
Node.js / LEARN BY DOING

Node.js 事件循环

核对 Node.js 事件循环六阶段顺序、微任务与宏任务优先级(process.nextTick 与 Promise.then)、I/O 回调内 setImmediate 先于 setTimeout 的确定性规律及事件驱动程序机制。

学完这一章,你能够

  • 核对 Node.js 事件循环六阶段顺序、微任务与宏任务优先级(process.nextTick 与 Promise.then)、I/O 回调内 setImmediate 先于 setTimeout 的确定性规律及事件驱动程序机制。

事件循环的核心作用与六个阶段

事件循环(Event Loop)是 Node.js 单线程运行时支撑非阻塞 I/O 与高并发连接的核心引擎。它将文件读写、网络请求和数据库查询委托给底层异步机制,在单线程内循环调度完成回调,避免线程长时间阻塞。

libuv 事件循环按固定顺序流转六个阶段:1)`Timers` 执行到期的 `setTimeout()` 与 `setInterval()` 回调;2)`I/O Callbacks`(Pending Callbacks)处理延迟到下一轮的系统级 I/O 回调;3)`Idle, prepare` 供内部调度使用;4)`Poll` 检索新到达的 I/O 事件并执行对应回调;5)`Check` 执行 `setImmediate()` 回调;6)`Close Callbacks` 处理如 `socket.on('close', ...)` 等关闭回调。

任务进入对应阶段队列后由事件循环逐阶段推进,并在 `Poll` 阶段按需等待新事件或转向检查其他阶段。需要特别注意:`setTimeout(..., 0)` 与 `setImmediate()` 若在主模块顶层同时注册,受进程启动定时器阈值影响先后并不固定;但若注册在 I/O 回调(`Poll` 阶段)内部,下一阶段必先经过 `Check` 再回到 `Timers`,因此 `setImmediate()` 必然严格先于 `setTimeout(..., 0)` 执行。本站 Node.js v24.22.3 在 `fs.readFile` 回调内实测顺序固定为 `['io_sync', 'nextTick_in_io', 'promise_in_io', 'setImmediate', 'setTimeout_0']`。

宏任务、微任务与 process.nextTick 优先级

在调度优先级上,宏任务包含 `setTimeout`、`setInterval`、`setImmediate` 与 I/O 回调,微任务包含 `process.nextTick` 与 `Promise.then`。微任务优先级高于宏任务,会在当前阶段回调返回后、进入下一阶段前清空;在同一轮事件循环回调内,`process.nextTick()` 队列优先于 `Promise.then` 微任务(若在已处于微任务清空过程的顶层 `await` 恢复点中注册,则当轮 Promise 微任务可能先清空)。本站在独立事件循环轮次内实测完整顺序为 `['main_sync', 'next_tick', 'promise_then', 'timeout_0']`。

事件驱动程序模型与 Node.js 应用工作流

Node.js 的事件驱动编程以 `events` 模块中的 `EventEmitter` 类为核心,思路类似观察者模式:事件代表状态变化或动作(如文件读完、请求到达),`EventEmitter` 负责注册与触发,事件处理器即绑定的回调函数。通过“注册事件 → 触发事件 → 调度处理器”三步即可构建高内聚的解耦逻辑。

实例化 `new EventEmitter()` 后通过 `.on(eventName, handler)` 绑定处理器、通过 `.emit(eventName)` 触发。需留意 `emit()` 本身是同步调用监听器:实测在 `connection` 监听器内继续触发 `data_received` 时,严格按同步顺序产出 `['connected', 'data_received', 'program_done']`。

在典型 Node.js 异步应用中,函数以回调作为末参、以错误对象 `err` 作为回调首参。以 `fs.readFile` 读取临时文件为例:文件存在时先打印主线程收尾再输出文件内容(实测 `['dispatched', 'data:event-loop-io-data']`);删除该文件后再次读取,主流程同样先输出收尾,回调随后接收并报告缺失文件错误(实测 `['dispatched', 'err:ENOENT']`)。

实测微任务/宏任务优先级、I/O 回调内 setImmediate 与 setTimeout 顺序及事件驱动流转

含完整源码 · 138 行
展开查看收起
javascript
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mbsky-node-loop-'));

try {
  const inputPath = path.join(tmpDir, 'input.txt');
  await fsp.writeFile(inputPath, 'event-loop-io-data', 'utf8');

  // Case 1: Microtask (nextTick > Promise.then) vs Macrotask (setTimeout 0) in a fresh event-loop turn
  const order1 = await new Promise((resolve) => {
    setImmediate(() => {
      const seq = [];
      setTimeout(() => {
        seq.push('timeout_0');
        resolve(seq);
      }, 0);
      Promise.resolve().then(() => {
        seq.push('promise_then');
      });
      process.nextTick(() => {
        seq.push('next_tick');
      });
      seq.push('main_sync');
    });
  });

  const actual1 = { order: order1 };
  const expected1 = { order: ['main_sync', 'next_tick', 'promise_then', 'timeout_0'] };

  // Case 2: Inside Poll I/O callback, setImmediate (Check phase) deterministically precedes setTimeout(0) (Timers phase)
  const order2 = await new Promise((resolve, reject) => {
    fs.readFile(inputPath, 'utf8', (err) => {
      if (err) return reject(err);
      const seq = [];
      let doneCount = 0;
      const finish = () => {
        doneCount += 1;
        if (doneCount === 2) resolve(seq);
      };

      setTimeout(() => {
        seq.push('setTimeout_0');
        finish();
      }, 0);

      setImmediate(() => {
        seq.push('setImmediate');
        finish();
      });

      Promise.resolve().then(() => {
        seq.push('promise_in_io');
      });

      process.nextTick(() => {
        seq.push('nextTick_in_io');
      });

      seq.push('io_sync');
    });
  });

  const actual2 = { order: order2 };
  const expected2 = {
    order: ['io_sync', 'nextTick_in_io', 'promise_in_io', 'setImmediate', 'setTimeout_0'],
  };

  // Case 3: EventEmitter synchronous event dispatch & chained events
  const emitter = new EventEmitter();
  const eventLog = [];
  emitter.on('connection', () => {
    eventLog.push('connected');
    emitter.emit('data_received');
  });
  emitter.on('data_received', () => {
    eventLog.push('data_received');
  });
  emitter.emit('connection');
  eventLog.push('program_done');

  const actual3 = { eventLog };
  const expected3 = { eventLog: ['connected', 'data_received', 'program_done'] };

  // Case 4: Non-blocking fs.readFile success and ENOENT after deleting file
  const okLog = await new Promise((resolve) => {
    const seq = [];
    fs.readFile(inputPath, 'utf8', (err, data) => {
      if (err) {
        seq.push(`err:${err.code}`);
      } else {
        seq.push(`data:${data}`);
      }
      resolve(seq);
    });
    seq.push('dispatched');
  });

  await fsp.unlink(inputPath);

  const missingLog = await new Promise((resolve) => {
    const seq = [];
    fs.readFile(inputPath, 'utf8', (err, data) => {
      if (err) {
        seq.push(`err:${err.code}`);
      } else {
        seq.push(`data:${data}`);
      }
      resolve(seq);
    });
    seq.push('dispatched');
  });

  const actual4 = { okLog, missingLog };
  const expected4 = {
    okLog: ['dispatched', 'data:event-loop-io-data'],
    missingLog: ['dispatched', 'err:ENOENT'],
  };

  const cases = [
    { name: 'microtask_vs_macrotask_priority', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
    { name: 'io_callback_immediate_before_timeout', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
    { name: 'event_emitter_sync_dispatch', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
    { name: 'async_readfile_success_and_enoent', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
  ];

  console.log(JSON.stringify({ version: process.version, cases }));
} finally {
  await fsp.rm(tmpDir, { recursive: true, force: true });
}
核对 ['main_sync','next_tick','promise_then','timeout_0']、I/O 内 setImmediate 先于 setTimeout(0)、EventEmitter 同步链式触发及 fs.readFile 正常与 ENOENT 路径。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1048.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1048.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为 fs.readFile 回调处于 Poll 阶段,Poll 结束后事件循环必然先进入 Check 阶段执行 setImmediate,再进入下一轮循环的 Timers 阶段执行 setTimeout;EventEmitter.emit() 按注册顺序同步调用所有监听器。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习