Run JavaScript
import { PackageManagers, Render, Steps, TypeScriptExample, WranglerConfig, } from "~/components";
You will POST JavaScript to a Worker and read {"result":["Ada"]}.
Prerequisites
Run JavaScript
-
Create a Worker project:
<PackageManagers type="create" pkg="cloudflare@latest" args={"sandbox-dynamic-worker --category=hello-world --type=hello-world --lang=ts --no-deploy"} />
-
Change into the project directory:
cd sandbox-dynamic-worker -
Replace
wrangler.jsoncto add a Worker Loader binding:{ "$schema": "node_modules/wrangler/config-schema.json", "name": "sandbox-dynamic-worker", "main": "src/index.ts", "compatibility_date": "$today", "observability": { "enabled": true, }, "upload_source_maps": true, "worker_loaders": [ { "binding": "LOADER", }, ], } -
Generate types for the binding:
-
Replace
src/index.ts. Your Worker readscodefrom the JSON body and runs it in the sandbox:import type { WorkerEntrypoint } from "cloudflare:workers"; type CodeEntrypoint = WorkerEntrypoint & { evaluate(): Promise<unknown>; }; export default { async fetch(request: Request, env: Env): Promise<Response> { const { code } = (await request.json()) as { code: string }; const sandbox = env.LOADER.load({ compatibilityDate: "$today", mainModule: "code.js", modules: { "code.js": ` import { WorkerEntrypoint } from "cloudflare:workers"; export class Code extends WorkerEntrypoint { evaluate() { ${code} } } `, }, // Block `fetch()` and `connect()` globalOutbound: null, // Stop code that uses more than 50 milliseconds of CPU time limits: { cpuMs: 50 }, }); const result = await sandbox .getEntrypoint<CodeEntrypoint>("Code") .evaluate(); return Response.json({ result }); }, };codeis the body ofevaluate(), so it needs areturnstatement. Code that waits without using CPU can still hold the request open, so add a timeout before you run code from other people. For an example, refer to Build an AI code interpreter. -
Run
wrangler dev: -
POST JavaScript to the URL Wrangler prints. The default is
http://localhost:8787:curl http://localhost:8787 --request POST --json '{ "code": "const users = [{ name: \"Ada\", role: \"admin\" }, { name: \"Grace\", role: \"user\" }]; return users.filter((u) => u.role === \"admin\").map((u) => u.name);" }'
The response body is {"result":["Ada"]}. The Worker ran the JavaScript you sent.
Next steps
- Let the code call methods that your Worker provides. Refer to Bindings.
- Run a Linux command. Refer to Run a Linux command.
- Use the Loader API for
load()andget().
谢谢你的反馈!