cloudflare-workers
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare Workers
Cloudflare Workers
Serverless platform for building applications across Cloudflare's global network.
一款可在Cloudflare全球网络上构建应用的无服务器平台。
Quick Navigation
快速导航
- Runtime & handlers →
references/runtime.md - Bindings overview →
references/bindings.md - Wrangler configuration →
references/wrangler.md - Local development →
references/local-dev.md - Static assets →
references/assets.md - Testing →
references/testing.md
- 运行时与处理器 →
references/runtime.md - 绑定概览 →
references/bindings.md - Wrangler配置 →
references/wrangler.md - 本地开发 →
references/local-dev.md - 静态资源 →
references/assets.md - 测试 →
references/testing.md
When to Use
适用场景
- Building serverless APIs or full-stack applications
- Running edge functions with global distribution
- Connecting to Cloudflare storage (KV, R2, D1, Durable Objects)
- Running AI inference with Workers AI
- Configuring Wrangler CLI and wrangler.toml
- Setting up local development with Miniflare
- Testing Workers with Vitest
- 构建无服务器API或全栈应用
- 运行具备全球分发能力的边缘函数
- 连接Cloudflare存储服务(KV、R2、D1、Durable Objects)
- 通过Workers AI运行AI推理
- 配置Wrangler CLI与wrangler.toml
- 基于Miniflare搭建本地开发环境
- 使用Vitest测试Workers
Module Worker (Recommended Syntax)
模块Worker(推荐语法)
typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response("Hello, World!");
},
} satisfies ExportedHandler<Env>;typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response("Hello, World!");
},
} satisfies ExportedHandler<Env>;Handler Types
处理器类型
| Handler | Trigger | Use Case |
|---|---|---|
| HTTP request | APIs, websites |
| Cron trigger | Background jobs |
| Queue message | Async processing |
| Email received | Email routing |
| 处理器 | 触发方式 | 适用场景 |
|---|---|---|
| HTTP请求 | API、网站 |
| Cron触发器 | 后台任务 |
| 队列消息 | 异步处理 |
| 收到邮件 | 邮件路由 |
Bindings Overview
绑定概览
Access Cloudflare resources via object.
env| Binding | Type | Local Dev |
|---|---|---|
| KV | | ✅ Simulated |
| R2 | | ✅ Simulated |
| D1 | | ✅ Simulated |
| Durable Objects | | ✅ Simulated |
| Queues | | ✅ Simulated |
| Workers AI | | ❌ Remote only |
| Vectorize | | ❌ Remote only |
| Browser Rendering | | ❌ Remote only |
| Hyperdrive | | ❌ Remote only |
| Static Assets | | ✅ Simulated |
| Service Binding | | ✅ Simulated |
通过对象访问Cloudflare资源。
env| 绑定类型 | 类型 | 本地开发支持 |
|---|---|---|
| KV | | ✅ 可模拟 |
| R2 | | ✅ 可模拟 |
| D1 | | ✅ 可模拟 |
| Durable Objects | | ✅ 可模拟 |
| Queues | | ✅ 可模拟 |
| Workers AI | | ❌ 仅支持远程 |
| Vectorize | | ❌ 仅支持远程 |
| Browser Rendering | | ❌ 仅支持远程 |
| Hyperdrive | | ❌ 仅支持远程 |
| 静态资源 | | ✅ 可模拟 |
| 服务绑定 | | ✅ 可模拟 |
Minimal Configuration
最简配置
jsonc
// wrangler.jsonc
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2025-03-07",
"compatibility_flags": ["nodejs_compat"],
"observability": {
"enabled": true,
"head_sampling_rate": 1
}
}jsonc
// wrangler.jsonc
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2025-03-07",
"compatibility_flags": ["nodejs_compat"],
"observability": {
"enabled": true,
"head_sampling_rate": 1
}
}Essential Commands
常用命令
bash
undefinedbash
undefinedDevelopment
开发
npx wrangler dev # Local dev (Miniflare)
npx wrangler dev --remote # Remote dev (code on Cloudflare)
npx wrangler dev # 本地开发(基于Miniflare)
npx wrangler dev --remote # 远程开发(代码部署在Cloudflare)
Deployment
部署
npx wrangler deploy # Deploy to production
npx wrangler versions upload # Upload without deploying
npx wrangler versions deploy # Promote version
npx wrangler deploy # 部署到生产环境
npx wrangler versions upload # 上传版本但不部署
npx wrangler versions deploy # 推广版本至生产
Secrets
密钥管理
npx wrangler secret put KEY # Add secret
npx wrangler secret list # List secrets
npx wrangler secret put KEY # 添加密钥
npx wrangler secret list # 列出所有密钥
Types
类型生成
npx wrangler types # Generate TypeScript types
undefinednpx wrangler types # 生成TypeScript类型定义
undefinedCompatibility Settings
兼容性设置
toml
undefinedtoml
undefinedwrangler.toml
wrangler.toml
compatibility_date = "2025-03-07"
compatibility_flags = ["nodejs_compat"]
Key flags:
- `nodejs_compat` — Enable Node.js APIs
- `nodejs_compat_v2` — Improved process implementationcompatibility_date = "2025-03-07"
compatibility_flags = ["nodejs_compat"]
关键标志:
- `nodejs_compat` — 启用Node.js API
- `nodejs_compat_v2` — 改进的进程实现Quick Recipes
快速示例
Fetch Handler with Routing
带路由的Fetch处理器
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/api/hello") {
return Response.json({ message: "Hello!" });
}
if (url.pathname.startsWith("/static/")) {
return env.ASSETS.fetch(request);
}
return new Response("Not Found", { status: 404 });
},
};typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/api/hello") {
return Response.json({ message: "Hello!" });
}
if (url.pathname.startsWith("/static/")) {
return env.ASSETS.fetch(request);
}
return new Response("Not Found", { status: 404 });
},
};Scheduled Handler (Cron)
Scheduled处理器(Cron)
typescript
export default {
async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) {
ctx.waitUntil(doBackgroundWork(env));
},
};toml
undefinedtypescript
export default {
async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) {
ctx.waitUntil(doBackgroundWork(env));
},
};toml
undefinedwrangler.toml
wrangler.toml
[triggers]
crons = ["0 * * * *"] # Every hour
undefined[triggers]
crons = ["0 * * * *"] # 每小时执行一次
undefinedQueue Consumer
队列消费者
typescript
export default {
async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext) {
for (const message of batch.messages) {
console.log(message.body);
message.ack();
}
},
};typescript
export default {
async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext) {
for (const message of batch.messages) {
console.log(message.body);
message.ack();
}
},
};Critical Prohibitions
重要禁忌
- Do NOT store secrets in — use
wrangler.tomlwrangler secret put - Do NOT use for Durable Objects or Workflows — unsupported
remote: true - Do NOT expect Workers AI to work locally — always requires remote connection
- Do NOT omit — defaults to oldest date (2021-11-02)
compatibility_date - Do NOT use Service Worker syntax for new projects — use ES Modules
- Do NOT mix Service Worker and Module syntax in same project
- 请勿在中存储密钥 — 使用
wrangler.toml命令wrangler secret put - 请勿对Durable Objects或Workflows设置— 该配置不被支持
remote: true - 请勿期望Workers AI在本地运行 — 始终需要远程连接
- 请勿省略— 默认值为最早版本日期(2021-11-02)
compatibility_date - 新项目请勿使用Service Worker语法 — 请使用ES Modules
- 请勿在同一项目中混合使用Service Worker与Module语法
Common Gotchas
常见问题与解决方法
| Issue | Solution |
|---|---|
| Local bindings empty | Add |
| AI not working locally | Use |
| Node APIs unavailable | Add |
| First deploy fails | Use |
| 问题 | 解决方案 |
|---|---|
| 本地绑定为空 | 在Wrangler的KV/R2/D1命令中添加 |
| AI在本地无法工作 | 在AI绑定配置中设置 |
| Node API无法使用 | 在compatibility_flags中添加 |
| 首次部署失败 | 首次部署请使用 |
Related Skills
相关技能
- — Full-stack hosting with Git deployment
cloudflare-pages - — D1 database operations
cloudflare-d1 - — R2 object storage
cloudflare-r2 - — KV namespace operations
cloudflare-kv - — Stateful coordination
cloudflare-durable-objects
- — 支持Git部署的全栈托管服务
cloudflare-pages - — D1数据库操作
cloudflare-d1 - — R2对象存储
cloudflare-r2 - — KV命名空间操作
cloudflare-kv - — 有状态协调服务
cloudflare-durable-objects