Skip to content

Adapter 助手

Adapter 助手通过统一的接口,让你可以无缝访问不同平台。

导入

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

env()

env() 函数用于在不同运行时中获取环境变量,适用范围不仅限于 Cloudflare Workers 的 Bindings。env(c) 返回的值会随着运行时而有所不同。

ts
import { env } from 'hono/adapter'

app.get('/env', (c) => {
  // 在 Node.js 或 Bun 中,NAME 对应 process.env.NAME
  // 在 Cloudflare 中,NAME 来自 `wrangler.toml`
  const { NAME } = env<{ NAME: string }>(c)
  return c.text(NAME)
})

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

指定运行时

你可以将运行时键作为第二个参数传入,以便从指定的运行时读取环境变量。

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 的 Runtime Keys 提案

  • workerd - Cloudflare Workers
  • deno
  • bun
  • node
  • edge-light - Vercel Edge Functions
  • fastly - Fastly Compute
  • other - 其他未知运行时键

Released under the MIT License.