跳转到正文

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)
})

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

指定运行时 ​

可以将运行时标识作为第二个参数传入,指定获取环境变量所用的运行时。

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 Workers
  • deno
  • bun
  • node
  • edge-light - Vercel Edge Functions
  • fastly - Fastly Compute
  • other - 其他未知运行时标识

基于 MIT 许可证发布。