Cloudflare Workers
History
| Version | Changes | 
|---|---|
| v3.13.0 | 
先决条件
¥Prerequisites
- 
Cloudflare 账户。 ¥A Cloudflare account. 
- 
Wrangler 已安装。 ¥Wrangler installed. 
- 
MySQL2 版本 3.13.0或更高版本。¥MySQL2 version 3.13.0or higher.
要了解如何创建 Cloudflare Worker 项目,请参阅 Cloudflare Workers 文档。
¥To learn how to create a Cloudflare Worker project, please refer to Cloudflare Workers Documentation.
设置
¥Setup
Wrangler
MySQL2 依赖于 Node.js 模块,例如 net、events、stream、tls 等。你可以通过 wrangler.jsonc 文件使用 "nodejs_compat" 标志为 Cloudflare Workers 启用 Node.js 兼容性:
¥MySQL2 relies on Node.js modules, such as net, events, stream, tls, etc. You can enable Node.js compatibility for Cloudflare Workers by using the "nodejs_compat" flag through the wrangler.jsonc file:
{
  "compatibility_flags": ["nodejs_compat"]
}
最低兼容日期为 2025-02-24,例如:
¥The minimum compatibility date is 2025-02-24, for example:
{
  "compatibility_date": "2025-02-24",
  "compatibility_flags": ["nodejs_compat"]
}
MySQL2 连接
¥MySQL2 connection
MySQL2 默认使用基于代码生成的解析器来提高性能,但由于 Cloudflare Workers 不提供评估支持,你可以使用 disableEval 选项禁用它:
¥MySQL2 uses a code generation-based parser for performance by default, but since Cloudflare Workers don't offer support for evaluations, you can disable it by using the disableEval option:
import { createConnection } from 'mysql2/promise';
export default {
  async fetch(): Promise<Response> {
    const conn = await createConnection({
      host: 'localhost',
      user: 'root',
      database: 'test',
      disableEval: true,
    });
    const [results] = await conn.query('SHOW TABLES;');
    return new Response(JSON.stringify(results));
  },
} satisfies ExportedHandler<Env>;
对于所需的 SSL 连接,建议使用 Cloudflare Hyperdrive 连接池。
¥For required SSL connections, it is recommended to use the Cloudflare Hyperdrive connection pool.