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