Adapter 辅助工具
Adapter 辅助工具提供统一的接口,让你轻松与各种平台交互。
导入
ts
import { Hono } from 'hono'
import { env, getRuntimeKey } from 'hono/adapter'env()
env() 函数用于在不同运行时中获取环境变量,其用途不限于 Cloudflare Workers 的绑定。通过 env(c) 获取的值可能因运行时而异。
ts
import { env } from 'hono/adapter'
app.get('/env', (c) => {
// NAME is process.env.NAME on Node.js or Bun
// NAME is the value written in `wrangler.toml` on Cloudflare
const { NAME } = env<{ NAME: string }>(c)
return c.text(NAME)
})支持的运行时、无服务器平台和云服务:
- Cloudflare Workers
wrangler.tomlwrangler.jsonc
- Deno
Deno.env.env文件
- Bun
Bun.envprocess.env
- Node.js
process.env
- Vercel
- AWS Lambda
- Lambda@Edge
Lambda@Edge 不支持 Lambda 环境变量,需要改用 Lambda@Edge 事件。 - Fastly Compute
在 Fastly Compute 上,可以使用 ConfigStore 管理用户定义的数据。 - Netlify
在 Netlify 上,可以使用 Netlify 上下文管理用户定义的数据。
指定运行时
可以将运行时标识作为第二个参数传入,指定获取环境变量所用的运行时。
ts
app.get('/env', (c) => {
const { NAME } = env<{ NAME: string }>(c, 'workerd')
return c.text(NAME)
})getRuntimeKey()
getRuntimeKey() 函数返回当前运行时的标识。
ts
app.get('/', (c) => {
if (getRuntimeKey() === 'workerd') {
return c.text('You are on Cloudflare')
} else if (getRuntimeKey() === 'bun') {
return c.text('You are on Bun')
}
...
})可用的运行时标识
以下是可用的运行时标识。没有对应标识的运行时也可能受到支持,并标为 other。其中部分标识参考了 WinterCG 的运行时标识:
workerd- Cloudflare Workersdenobunnodeedge-light- Vercel Edge Functionsfastly- Fastly Computeother- 其他未知运行时标识