workers-migration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWorkers Migration Guide
Workers迁移指南
Migrate existing applications to Cloudflare Workers from various platforms.
将现有应用从多种平台迁移至Cloudflare Workers。
Migration Decision Tree
迁移决策树
What are you migrating from?
├── AWS Lambda
│ └── Node.js handler? → Lambda adapter pattern
│ └── Python? → Consider Python Workers
│ └── Container/custom runtime? → May need rewrite
├── Vercel/Next.js
│ └── API routes? → Minimal changes with adapter
│ └── Full Next.js app? → Use OpenNext adapter
│ └── Middleware? → Direct Workers equivalent
├── Express/Node.js
│ └── Simple API? → Hono (similar API)
│ └── Complex middleware? → Gradual migration
│ └── Heavy node: usage? → Compatibility layer
└── Other Edge (Deno Deploy, Fastly)
└── Standard Web APIs? → Minimal changes
└── Platform-specific? → Targeted rewrites你要从哪个平台迁移?
├── AWS Lambda
│ └── Node.js 处理器?→ Lambda 适配器模式
│ └── Python?→ 考虑使用Python Workers
│ └── 容器/自定义运行时?→ 可能需要重写
├── Vercel/Next.js
│ └── API 路由?→ 使用适配器只需少量修改
│ └── 完整Next.js应用?→ 使用OpenNext适配器
│ └── 中间件?→ 直接使用Workers等效方案
├── Express/Node.js
│ └── 简单API?→ 使用Hono(API风格类似)
│ └── 复杂中间件?→ 逐步迁移
│ └── 大量使用node:模块?→ 使用兼容层
└── 其他边缘平台(Deno Deploy、Fastly)
└── 标准Web API?→ 只需少量修改
└── 平台特定API?→ 针对性重写Platform Comparison
平台对比
| Feature | Workers | Lambda | Vercel | Express |
|---|---|---|---|---|
| Cold Start | ~0ms | 100-500ms | 10-100ms | N/A |
| CPU Limit | 50ms/10ms | 15 min | 10s | None |
| Memory | 128MB | 10GB | 1GB | System |
| Max Response | 6MB (stream unlimited) | 6MB | 4.5MB | None |
| Global Edge | 300+ PoPs | Regional | ~20 PoPs | Manual |
| Node.js APIs | Partial | Full | Full | Full |
| 特性 | Workers | Lambda | Vercel | Express |
|---|---|---|---|---|
| 冷启动 | ~0ms | 100-500ms | 10-100ms | 不适用 |
| CPU限制 | 50ms/10ms | 15分钟 | 10秒 | 无 |
| 内存 | 128MB | 10GB | 1GB | 系统分配 |
| 最大响应大小 | 6MB(流式传输无限制) | 6MB | 4.5MB | 无 |
| 全球边缘节点 | 300+ PoPs | 区域节点 | ~20 PoPs | 手动配置 |
| Node.js APIs | 部分支持 | 完全支持 | 完全支持 | 完全支持 |
Top 10 Migration Errors
十大常见迁移错误
| Error | From | Cause | Solution |
|---|---|---|---|
| Lambda/Express | File system access | Use KV/R2 for storage |
| Node.js | Node.js globals | Import from |
| All | Env access pattern | Use |
| Lambda | Async patterns | Use |
| Express | CommonJS | Convert to ESM imports |
| All | Long computation | Chunk or use DO |
| Express | Request body | Clone before read |
| Lambda | Headers API | Use Headers constructor |
| Node.js | Node crypto | Use |
| All | Missing polyfill | Check Workers compatibility |
| 错误 | 来源平台 | 原因 | 解决方案 |
|---|---|---|---|
| Lambda/Express | 文件系统访问 | 使用KV/R2进行存储 |
| Node.js | Node.js全局变量 | 从 |
| 所有平台 | 环境变量访问方式 | 使用 |
| Lambda | 异步模式问题 | 使用 |
| Express | CommonJS语法 | 转换为ESM导入 |
| 所有平台 | 计算任务过长 | 拆分任务或使用DO |
| Express | 请求体读取问题 | 读取前先克隆请求 |
| Lambda | Headers API差异 | 使用Headers构造函数 |
| Node.js | Node加密模块 | 使用 |
| 所有平台 | 缺少polyfill | 检查Workers兼容性 |
Quick Migration Patterns
快速迁移模式
AWS Lambda Handler
AWS Lambda处理器
typescript
// Before: AWS Lambda
export const handler = async (event, context) => {
const body = JSON.parse(event.body);
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello' }),
};
};
// After: Cloudflare Workers
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const body = await request.json();
return Response.json({ message: 'Hello' });
},
};typescript
// Before: AWS Lambda
export const handler = async (event, context) => {
const body = JSON.parse(event.body);
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello' }),
};
};
// After: Cloudflare Workers
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const body = await request.json();
return Response.json({ message: 'Hello' });
},
};Express Middleware
Express中间件
typescript
// Before: Express
app.use((req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
});
// After: Hono Middleware
app.use('*', async (c, next) => {
if (!c.req.header('Authorization')) {
return c.json({ error: 'Unauthorized' }, 401);
}
await next();
});typescript
// Before: Express
app.use((req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
});
// After: Hono Middleware
app.use('*', async (c, next) => {
if (!c.req.header('Authorization')) {
return c.json({ error: 'Unauthorized' }, 401);
}
await next();
});Environment Variables
环境变量
typescript
// Before: Node.js
const apiKey = process.env.API_KEY;
// After: Workers
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const apiKey = env.API_KEY;
// ...
},
};typescript
// Before: Node.js
const apiKey = process.env.API_KEY;
// After: Workers
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const apiKey = env.API_KEY;
// ...
},
};Node.js Compatibility
Node.js兼容性
Workers support many Node.js APIs via compatibility flags:
jsonc
// wrangler.jsonc
{
"compatibility_flags": ["nodejs_compat_v2"],
"compatibility_date": "2024-12-01"
}Supported with nodejs_compat_v2:
- (most methods)
crypto - (Buffer class)
buffer - (promisify, types)
util - (Readable, Writable)
stream - (EventEmitter)
events - (all methods)
path string_decoderassert
Not Supported (need alternatives):
- → Use R2/KV
fs - → Not possible
child_process - → Not applicable
cluster - → Not supported
dgram - → Use fetch/WebSocket
net - → Handled by platform
tls
Workers通过兼容性标志支持众多Node.js API:
jsonc
// wrangler.jsonc
{
"compatibility_flags": ["nodejs_compat_v2"],
"compatibility_date": "2024-12-01"
}nodejs_compat_v2支持的API:
- (大部分方法)
crypto - (Buffer类)
buffer - (promisify、类型相关)
util - (Readable、Writable)
stream - (EventEmitter)
events - (所有方法)
path string_decoderassert
不支持的API(需使用替代方案):
- → 使用R2/KV
fs - → 无法使用
child_process - → 不适用
cluster - → 不支持
dgram - → 使用fetch/WebSocket
net - → 由平台自动处理
tls
When to Load References
何时加载参考文档
| Reference | Load When |
|---|---|
| Migrating AWS Lambda functions |
| Migrating from Vercel/Next.js |
| Migrating Express/Node.js apps |
| Node.js API compatibility issues |
| 参考文档 | 加载场景 |
|---|---|
| 迁移AWS Lambda函数时 |
| 从Vercel/Next.js迁移时 |
| 迁移Express/Node.js应用时 |
| 遇到Node.js API兼容性问题时 |
Migration Checklist
迁移检查清单
- Analyze Dependencies: Check for unsupported Node.js APIs
- Convert to ESM: Replace require() with import
- Update Env Access: Use env parameter instead of process.env
- Replace File System: Use R2/KV for storage
- Handle Async: Use ctx.waitUntil() for background tasks
- Test Locally: Verify with wrangler dev
- Performance Test: Ensure CPU limits aren't exceeded
- 分析依赖项:检查是否存在不支持的Node.js API
- 转换为ESM:将require()替换为import
- 更新环境变量访问方式:使用env参数替代process.env
- 替换文件系统:使用R2/KV进行存储
- 处理异步任务:使用ctx.waitUntil()处理后台任务
- 本地测试:使用wrangler dev验证
- 性能测试:确保未超出CPU限制
See Also
另请参阅
- - Available APIs in Workers
workers-runtime-apis - - Optimization techniques
workers-performance - - Basic Workers setup
cloudflare-worker-base
- - Workers中可用的API
workers-runtime-apis - - 优化技巧
workers-performance - - Workers基础设置
cloudflare-worker-base