踩坑实录:Edge Runtime 的限制
踩坑实录:Edge Runtime 的限制
我的代码本地跑得好好的,一部署到 Cloudflare Workers 就报错~
排查了半天,发现是 Edge Runtime 的问题。
本地 Node.js ≠ Edge Runtime
什么是 Edge Runtime
Cloudflare Workers、Vercel Edge Functions 都运行在 Edge Runtime。
它比 Node.js 快(冷启动 < 5ms),但功能受限。
不支持的东西:
fs模块(不能读文件)path模块(路径处理受限)crypto的某些方法setTimeout超过 30 秒- 大内存操作(128MB 限制)
我踩的坑
场景:读配置文件
// 本地没问题
import fs from 'fs';
const config = JSON.parse(fs.readFileSync('./config.json'));
部署报错:
Error: No such module 'fs'
解决方案:把配置内联或用 KV
// 方案 1:内联
const config = { apiKey: 'xxx' };
// 方案 2:用 KV
const config = await env.KV.get('config');
另一个坑:超时限制
我的热点扫描脚本,GitHub Trending 响应慢,加上处理逻辑,跑了 35 秒。
本地没问题,Workers 直接 timeout。
解决方案:分批处理 + Durable Objects
// 分批,每批 < 30 秒
for (const source of sources) {
await fetchAndProcess(source);
}
或者用 Durable Objects,支持更长超时。
第三个坑:依赖包不兼容
用了 node-cron,部署报错:
Error: Cannot find module 'child_process'
因为 node-cron 依赖 Node.js 的 child_process,Edge Runtime 不支持。
解决方案:用 Edge 兼容的包
// 换成 schedulator(Edge 兼容)
import { Cron } from 'schedulator';
检查清单
部署到 Edge 前,检查这些:
- 没用
fs/path/child_process - 单个请求 < 30 秒
- 内存 < 128MB
- 依赖包标注 Edge 兼容
不确定的话,先在本地用 wrangler dev 模拟测试。
你的代码踩过 Edge Runtime 的坑吗~