So beheben Sie, dass AI die Cloudflare Workers Runtime stört
AI-Agenten importieren Node.js-Built-ins wie fs, crypto und path in Cloudflare Workers, was Laufzeitfehler verursacht, da die Workers Runtime nicht Node.js ist.
Der Agent schreibt Code, der lokal unter Node.js funktioniert, aber bei der Bereitstellung oder Laufzeit in Cloudflare Workers fehlschlägt, da die Workers Runtime eine V8-Isolate ist – nicht Node.js.
Das Symptom
Der Agent importiert Node.js-Built-ins oder npm-Pakete, die intern Node.js-APIs benötigen.
// 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')Warum passiert das?
Die meisten Trainingsdaten für Agenten zielen auf Node.js ab. Das Modell weiß, dass crypto, fs und path für Hashing, Dateizugriff und Pfadmanipulation funktionieren, also greift es darauf zu. Es unterscheidet nicht zwischen der Workers Runtime und Node.js, es sei denn, es wird explizit darauf hingewiesen.
Wie erkennt man es?
import ... from "crypto"/"fs"/"path"/"http"/"stream"in Worker-Dateien.wrangler devfunktioniert, aberwrangler deploywirft eine Bündelungswarnung wegen ungelöster Node.js-Module.- Der Abschnitt für Wrangler-Kompatibilitätsflags in
wrangler.tomlfehlt oder verwendet ein Datum vor dem2022-11-30. - Abhängigkeiten, die intern
require("node:...")ohne einen Workers-Kompatibilitäts-Shim verwenden.
Wie behebt man es?
Verwenden Sie Web-Standard-APIs – sie sind nativ in Workers verfügbar.
// 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 deployingBehebungshinweis
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.Test
# 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"