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 顺序及事件驱动流转
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 路径。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:83f675930ff37ef5b8b2c53b1ae298d0f58741da026ae98be266d4972d3ffe13
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:53af10773d70c584ef1078c2cb976142c6b616ab0af9e740e1c48977cadb6232
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 fs.readFile 回调内部同时调用 setTimeout(fn, 0) 和 setImmediate(fn) 时,总是 setImmediate 先执行?EventEmitter.emit() 是同步还是异步的?
展开参考解答
因为 fs.readFile 回调处于 Poll 阶段,Poll 结束后事件循环必然先进入 Check 阶段执行 setImmediate,再进入下一轮循环的 Timers 阶段执行 setTimeout;EventEmitter.emit() 按注册顺序同步调用所有监听器。