如何修复AI破坏Cloudflare Workers运行时的问题
AI代理将Node.js内置模块(如fs、crypto和path)导入Cloudflare Workers,导致运行时错误,因为Workers运行时不是Node.js。
CursorClaude CodeCodexWindsurf CloudflareTypeScript
代理编写的代码在本地Node.js环境下可以运行,但在Cloudflare Workers部署或运行时失败,因为Workers运行时是V8隔离环境——而非Node.js。
症状
代理导入Node.js内置模块或内部依赖Node.js API的npm包。
// worker.ts — WRONGimport { createHash } from "crypto"; // Node built-in — not availableimport { readFileSync } from "fs"; // Node built-in — not availableimport { resolve } from "path"; // Node built-in — not availableimport { IncomingMessage } from "http"; // Node built-in — not available
export default { async fetch(request: Request, env: Env) { const hash = createHash("sha256").update("data").digest("hex"); return new Response(hash); },};// Error at runtime: Cannot read properties of undefined (reading 'createHash')发生原因
大多数代理的训练数据针对Node.js。模型知道crypto、fs和path可用于哈希、文件访问和路径操作,因此会直接使用它们。除非明确告知,否则它不会区分Workers运行时和Node.js。
如何发现
- Worker文件中出现
import ... from "crypto"/"fs"/"path"/"http"/"stream"。 wrangler dev正常工作,但wrangler deploy抛出关于未解析Node.js模块的打包警告。wrangler.toml中的Wrangler兼容性标志部分缺失或使用的日期早于2022-11-30。- 依赖项内部使用
require("node:...")而没有Workers兼容性填充。
如何修复
使用Web标准API——它们在Workers中原生可用。
// worker.ts — CORRECTexport default { async fetch(request: Request, env: Env) { // Web Crypto API — standard, available in Workers const encoder = new TextEncoder(); const data = encoder.encode("data"); const hashBuffer = await crypto.subtle.digest("SHA-256", data); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hash = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); return new Response(hash); },};# wrangler.toml — enable Node.js compat shims for packages that need themcompatibility_date = "2024-09-23"compatibility_flags = ["nodejs_compat"][ ] No imports from "crypto", "fs", "path", "http", "stream", "os", "buffer" (use node: prefix + nodejs_compat flag if unavoidable)[ ] Use crypto.subtle for hashing/signing (Web Crypto API)[ ] Use env bindings (KV, R2, D1) instead of fs for storage[ ] Set compatibility_date to a recent date in wrangler.toml[ ] Add nodejs_compat flag only for third-party packages that require it[ ] Run "wrangler deploy --dry-run" to catch bundling errors before deploying修复提示
This code imports Node.js built-in modules (crypto, fs, path, http) that arenot available in the Cloudflare Workers runtime. Rewrite it using Web StandardAPIs: crypto.subtle for hashing/encryption, the Fetch API for HTTP, andCloudflare bindings (KV, R2, D1) for storage. If a third-party dependencyrequires Node.js APIs, add nodejs_compat to compatibility_flags in wrangler.tomland note that in a comment.测试
# Dry-run deploy to catch Node.js module errorswrangler deploy --dry-run --outdir dist 2>&1 | grep -i "error\|unresolved\|node:" && echo "FAIL" || echo "OK"
# Check for raw Node built-in importsgrep -rn '^import.*from "(crypto|fs|path|http|stream|os)"' src/ \ && echo "FAIL: Node.js built-in import found" || echo "OK"