Node.js 兼容与 node: 模块
在 Worker 里使用 npm 包和 Node.js 内置模块,理解 polyfill 与兼容日期。
它解决什么问题
让依赖 Node.js API 的 npm 包能跑在 Workers 上,同时知道哪些 API 只是占位实现。
一个具体例子
在 Worker 里用 node:crypto 计算摘要、用 Buffer 编码;兼容日期 2026-08-04 起默认开启,更早的日期要显式加 nodejs_compat。
你需要知道
- 兼容日期在 2026-08-04 及以后时 nodejs_compat 默认生效;2024-09-23 到 2026-08-03 需要显式加这个标记。
- 部分内置模块是 unenv 提供的 polyfill:能 import,但个别方法会抛错,必须实际调用验证。
- 文件系统、子进程、长连接等能力受限,需要对应产品(R2、Hyperdrive、容器)替代。
代码示例
// wrangler.jsonc(兼容日期 2024-09-23 ~ 2026-08-03)
{ "compatibility_flags": ["nodejs_compat"] }
// worker.js
import { Buffer } from 'node:buffer';
import { createHash } from 'node:crypto';
import { AsyncLocalStorage } from 'node:async_hooks';
const store = new AsyncLocalStorage();
export default {
async fetch(request) {
const digest = createHash('sha256').update('hello').digest('hex');
return Response.json({
digest,
base64: Buffer.from('workers').toString('base64'),
requestId: store.getStore()?.id ?? null
});
}
}动手试一下
- 先确认兼容日期:2026-08-04 之后默认开启,否则在配置里加 nodejs_compat。
- 从 node: 前缀导入模块,构建后确认 Wrangler 注入了对应实现。
- 本演示站部署在 2026-08-01 且没有开启这个标记,所以只提供说明,不提供在线运行。
预期结果:开启后同样的代码能返回摘要和 base64;未开启时 import 会在启动阶段失败。
注意:polyfill 不是完整实现,上线前请对真正用到的方法做一次真实调用测试。