# 如何修复AI破坏Cloudflare Workers运行时的问题

> AI代理将Node.js内置模块（如fs、crypto和path）导入Cloudflare Workers，导致运行时错误，因为Workers运行时不是Node.js。

**Type:** Failure  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Cloudflare, TypeScript  
**Updated:** 2026-06-08

---

代理编写的代码在本地Node.js环境下可以运行，但在Cloudflare Workers部署或运行时失败，因为Workers运行时是V8隔离环境——而非Node.js。

## 症状

代理导入Node.js内置模块或内部依赖Node.js API的npm包。

```ts
// worker.ts — WRONG
import { createHash } from "crypto";          // Node built-in — not available
import { readFileSync } from "fs";            // Node built-in — not available
import { resolve } from "path";              // Node built-in — not available
import { 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中原生可用。

```ts
// worker.ts — CORRECT
export 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);
  },
};
```

```toml
# wrangler.toml — enable Node.js compat shims for packages that need them
compatibility_date = "2024-09-23"
compatibility_flags = ["nodejs_compat"]
```

```txt
[ ] 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
```

## 修复提示

```txt title="Fix Prompt"
This code imports Node.js built-in modules (crypto, fs, path, http) that are
not available in the Cloudflare Workers runtime. Rewrite it using Web Standard
APIs: crypto.subtle for hashing/encryption, the Fetch API for HTTP, and
Cloudflare bindings (KV, R2, D1) for storage. If a third-party dependency
requires Node.js APIs, add nodejs_compat to compatibility_flags in wrangler.toml
and note that in a comment.
```

## 测试

```bash
# Dry-run deploy to catch Node.js module errors
wrangler deploy --dry-run --outdir dist 2>&1 | grep -i "error\|unresolved\|node:" && echo "FAIL" || echo "OK"

# Check for raw Node built-in imports
grep -rn '^import.*from "(crypto|fs|path|http|stream|os)"' src/ \
  && echo "FAIL: Node.js built-in import found" || echo "OK"
```