适配器帮助程序

Adapter Helper 提供了一种通过统一界面与各种平台交互的无缝方式。

进口

1
2
import { Hono } from 'hono'
import { env, getRuntimeKey } from 'hono/adapter'

env()

该函数有助于跨不同运行时检索环境变量,不仅限于 Cloudflare Workers’ Bindings。每个运行时的可检索值可能不同。env()``env(c)

1
2
3
4
5
6
7
8
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 NAME 与定义变量名一致,取完在赋值其他变量
const { NAME } = env<{ NAME: string }>(c)
return c.text(NAME)
})

支持的运行时、无服务器平台和云服务:

指定运行时

您可以通过将运行时键作为第二个参数传递来指定运行时以获取环境变量。

1
2
3
4
app.get('/env', (c) => {
const { NAME } = env<{ NAME: string }>(c, 'workerd')
return c.text(NAME)
})

getRuntimeKey()

该函数返回当前运行时的标识符。getRuntimeKey()

1
2
3
4
5
6
7
8
app.get('/', (c) => {
if (getRuntimeKey() === 'workerd') {
return c.text('You are on Cloudflare')
} else if (getRuntimeKey() === 'bun') {
return c.text('You are on Bun')
}
...
})

可用的 Runtimes 键

以下是可用的运行时密钥,不可用的运行时密钥运行时可能受支持并标记为 ,其中一些受到 WinterCG 的运行时密钥的启发:other

  • workerd- Cloudflare 工人

  • deno

  • bun

  • node

  • edge-light- Vercel Edge 函数

  • fastly- 快速计算

  • other- 其他未知的运行时键

在 GitHub 上编辑此页