Deno
Deno 是一个基于 V8 的 JavaScript 运行时。它不是 Node.js。Hono 也可以运行在 Deno 上。
你可以使用 Hono,通过 TypeScript 编写代码,用 deno
命令运行应用,并部署到 “Deno Deploy”。
1. 安装 Deno
首先,安装 deno
命令。请参考 官方文档。
2. 初始化项目
Deno 提供了 Starter 模板。通过以下命令启动项目:
deno init --npm hono my-app
此示例中选择 deno
模板。
进入 my-app
目录。对于 Deno,无需单独安装 Hono。
cd my-app
3. 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
修改端口号
可以通过修改 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.png
rewriteRequestPath
如果想把 http://localhost: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 的边缘运行平台,可以将应用发布到全球。 Hono 也支持 Deno Deploy。更多详情请查看 官方文档。
测试
Deno 的测试非常简单,可以使用 Deno.test
和 @std/assert 中的 assert
或 assertEquals
。
安装断言库:
deno add jsr:@std/assert
示例测试:
import { 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('http://localhost/')
assertEquals(res.status, 200)
})
运行测试:
deno test hello.ts
npm:
规范
npm:hono
也可用。可通过修改 deno.json
使用:
{
"imports": {
"hono": "jsr:@hono/hono"
"hono": "npm:hono"
}
}
你可以使用 npm:hono
或 jsr:@hono/hono
。
如果要使用第三方 Middleware,例如 npm:@hono/zod-validator
,并需要 TypeScript 类型推导,就必须使用 npm:
规范。
{
"imports": {
"hono": "npm:hono",
"zod": "npm:zod",
"@hono/zod-validator": "npm:@hono/zod-validator"
}
}