Deno
Deno 是一个基于 V8 的 JavaScript 运行时。它不是 Node.js。Hono 也适用于 Deno。
您可以使用 Hono,使用 TypeScript 编写代码,使用 deno 命令运行应用程序,并将其部署到“Deno Deploy”。
1. 安装 Deno
首先,安装 deno 命令。请参考 官方文档。
2. 设置
Deno 的入门程序可用。使用“create-hono”命令开始您的项目。
deno run -A npm:create-hono my-app选择 deno 模板作为本例。
移动到 my-app。对于 Deno,您无需显式安装 Hono。
cd my-app3. Hello World
编写您的第一个应用程序。
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Deno!'))
Deno.serve(app.fetch)4. 运行
只需此命令
deno task start更改端口号
您可以通过更新 main.ts 中 Deno.serve 的参数来指定端口号
Deno.serve(app.fetch)
Deno.serve({ port: 8787 }, app.fetch) 提供静态文件
要提供静态文件,请使用从 hono/middleware.ts 导入的 serveStatic。
import { Hono } from 'hono'
import { serveStatic } from 'hono/deno'
const app = new Hono()
app.use('/static/*', serveStatic({ root: './' }))
app.use('/favicon.ico', serveStatic({ path: './favicon.ico' }))
app.get('/', (c) => c.text('You can access: /static/hello.txt'))
app.get('*', serveStatic({ path: './static/fallback.txt' }))
Deno.serve(app.fetch)对于上面的代码,它将在以下目录结构下正常工作。
./
├── favicon.ico
├── index.ts
└── static
├── demo
│ └── index.html
├── fallback.txt
├── hello.txt
└── images
└── dinotocat.pngrewriteRequestPath
如果您想将 https://:8000/static/* 映射到 ./statics,您可以使用 rewriteRequestPath 选项
app.get(
'/static/*',
serveStatic({
root: './',
rewriteRequestPath: (path) =>
path.replace(/^\/static/, '/statics'),
})
)mimes
您可以使用 mimes 添加 MIME 类型
app.get(
'/static/*',
serveStatic({
mimes: {
m3u8: 'application/vnd.apple.mpegurl',
ts: 'video/mp2t',
},
})
)onFound
您可以使用 onFound 指定在找到请求的文件时的处理方式
app.get(
'/static/*',
serveStatic({
// ...
onFound: (_path, c) => {
c.header('Cache-Control', `public, immutable, max-age=31536000`)
},
})
)onNotFound
您可以使用 onNotFound 指定在未找到请求的文件时的处理方式
app.get(
'/static/*',
serveStatic({
onNotFound: (path, c) => {
console.log(`${path} is not found, you access ${c.req.path}`)
},
})
)precompressed
precompressed 选项检查是否存在具有 .br 或 .gz 等扩展名的文件,并根据 Accept-Encoding 标头提供这些文件。它优先考虑 Brotli,然后是 Zstd 和 Gzip。如果没有,则提供原始文件。
app.get(
'/static/*',
serveStatic({
precompressed: true,
})
)Deno Deploy
Deno Deploy 是 Deno 的边缘运行时平台。我们可以在 Deno Deploy 上发布应用程序,使其在全球范围内可用。
Hono 也支持 Deno Deploy。请参考 官方文档。
测试
在 Deno 上测试应用程序很容易。您可以使用 Deno.test 编写代码,并使用来自 @std/assert 的 assert 或 assertEquals。
deno add @std/assertimport { Hono } from 'hono'
import { assertEquals } from '@std/assert'
Deno.test('Hello World', async () => {
const app = new Hono()
app.get('/', (c) => c.text('Please test me'))
const res = await app.request('https:///')
assertEquals(res.status, 200)
})然后运行命令
deno test hello.tsnpm: 指定符
npm:hono 也可用。您可以通过修复 deno.json 来使用它
{
"imports": {
"hono": "jsr:@hono/hono"
"hono": "npm:hono"
}
}您可以使用 npm:hono 或 jsr:@hono/hono。
如果您想使用带 TypeScript 类型推断的第三方中间件,例如 npm:@hono/zod-validator,您需要使用 npm: 指定符。
{
"imports": {
"hono": "npm:hono",
"zod": "npm:zod",
"@hono/zod-validator": "npm:@hono/zod-validator"
}
}