Skip to content

Deno

Deno 是基于 V8 构建的 JavaScript 运行时。它不是 Node.js。Hono 也适用于 Deno。

¥Deno is a JavaScript runtime built on V8. It's not Node.js. Hono also works on Deno.

你可以使用 Hono,用 TypeScript 编写代码,使用 deno 命令运行应用,然后将其部署到 "Deno 部署"。

¥You can use Hono, write the code with TypeScript, run the application with the deno command, and deploy it to "Deno Deploy".

1. 安装 Deno

¥ Install Deno

首先,安装 deno 命令。请参考 官方文档

¥First, install deno command. Please refer to the official document.

2. 设置

¥ Setup

Deno 的启动器可用。使用 "create-hono" 命令启动你的项目。

¥A starter for Deno is available. Start your project with "create-hono" command.

sh
deno init --npm hono my-app

为此示例选择 deno 模板。

¥Select deno template for this example.

移入 my-app。对于 Deno,你不必明确安装 Hono。

¥Move into my-app. For Deno, you don't have to install Hono explicitly.

sh
cd my-app

3. Hello World

编写你的第一个应用。

¥Write your first application.

ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Deno!'))

Deno.serve(app.fetch)

4. 运行

¥ Run

只需这个命令:

¥Just this command:

sh
deno task start

更改端口编号

¥Change port number

你可以通过在 main.ts 中更新 Deno.serve 的参数来指定端口号:

¥You can specify the port number by updating the arguments of Deno.serve in main.ts:

ts
Deno.serve(app.fetch) 
Deno.serve({ port: 8787 }, app.fetch) 

提供静态文件

¥Serve static files

要提供静态文件,请使用从 hono/middleware.ts 导入的 serveStatic

¥To serve static files, use serveStatic imported from hono/middleware.ts.

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

对于上述代码,它将与以下目录结构配合良好。

¥For the above code, it will work well with the following directory structure.

./
├── favicon.ico
├── index.ts
└── static
    ├── demo
    │   └── index.html
    ├── fallback.txt
    ├── hello.txt
    └── images
        └── dinotocat.png

rewriteRequestPath

如果你想要将 http://localhost:8000/static/* 映射到 ./statics,你可以使用 rewriteRequestPath 选项:

¥If you want to map http://localhost:8000/static/* to ./statics, you can use the rewriteRequestPath option:

ts
app.get(
  '/static/*',
  serveStatic({
    root: './',
    rewriteRequestPath: (path) =>
      path.replace(/^\/static/, '/statics'),
  })
)

mimes

你可以使用 mimes 添加 MIME 类型:

¥You can add MIME types with mimes:

ts
app.get(
  '/static/*',
  serveStatic({
    mimes: {
      m3u8: 'application/vnd.apple.mpegurl',
      ts: 'video/mp2t',
    },
  })
)

onFound

你可以使用 onFound 指定找到请求的文件时的处理:

¥You can specify handling when the requested file is found with onFound:

ts
app.get(
  '/static/*',
  serveStatic({
    // ...
    onFound: (_path, c) => {
      c.header('Cache-Control', `public, immutable, max-age=31536000`)
    },
  })
)

onNotFound

你可以使用 onNotFound 指定未找到请求的文件时的处理:

¥You can specify handling when the requested file is not found with onNotFound:

ts
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。如果没有可用的目标,它将提供原始文件。

¥The precompressed option checks if files with extensions like .br or .gz are available and serves them based on the Accept-Encoding header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file.

ts
app.get(
  '/static/*',
  serveStatic({
    precompressed: true,
  })
)

Deno 部署

¥Deno Deploy

Deno Deploy 是 Deno 的边缘运行时平台。我们可以在 Deno Deploy 上向全世界发布应用。

¥Deno Deploy is an edge runtime platform for Deno. We can publish the application world widely on Deno Deploy.

Hono 还支持 Deno Deploy。请参考 官方文档

¥Hono also supports Deno Deploy. Please refer to the official document.

测试

¥Testing

在 Deno 上测试应用很容易。你可以使用 Deno.test 编写并使用 assertassertEquals(从 @std/assert 开始)。

¥Testing the application on Deno is easy. You can write with Deno.test and use assert or assertEquals from @std/assert.

sh
deno add jsr:@std/assert
ts
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)
})

然后运行命令:

¥Then run the command:

sh
deno test hello.ts

npm: 说明符

¥npm: specifier

npm:hono 也可用。你可以通过修复 deno.json 来使用它:

¥npm:hono is also available. You can use it by fixing the deno.json:

json
{
  "imports": {
    "hono": "jsr:@hono/hono"
    "hono": "npm:hono"
  }
}

你可以使用 npm:honojsr:@hono/hono

¥You can use either npm:hono or jsr:@hono/hono.

如果要将第三方中间件(如 npm:@hono/zod-validator)与 TypeScript 类型推断一起使用,则需要使用 npm: 说明符。

¥If you want to use Third-party Middleware such as npm:@hono/zod-validator with the TypeScript Type inferences, you need to use the npm: specifier.

json
{
  "imports": {
    "hono": "npm:hono",
    "zod": "npm:zod",
    "@hono/zod-validator": "npm:@hono/zod-validator"
  }
}

Hono v4.7 中文网 - 粤ICP备13048890号