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 的启动器可用。使用 deno init 命令启动你的项目。

¥A starter for Deno is available. Start your project with the deno init command.

sh
deno init --npm hono my-app --template=deno

移入 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

编辑 main.ts

¥Edit main.ts:

main.ts
ts
import { Hono } from 'hono'

const app = new Hono()

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

Deno.serve(app.fetch)

4. 运行

¥ Run

在本地运行开发服务器。然后,在你的 Web 浏览器中访问 http://localhost:8000

¥Run the development server locally. Then, access http://localhost:8000 in your Web browser.

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/deno 导入的 serveStatic

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

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 是一个用于在云端运行 JavaScript 和 TypeScript 应用的无服务器平台。它通过 GitHub 部署等集成,为部署和运行应用提供了一个管理面板。

¥Deno Deploy is a serverless platform for running JavaScript and TypeScript applications in the cloud. It provides a management plane for deploying and running applications through integrations like GitHub deployment.

Hono 也适用于 Deno Deploy。请参考 官方文档

¥Hono also works on 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
hello.ts
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 和 JSR

¥npm and JSR

Hono 在 npmJSR(JavaScript 注册表)上均可用。你可以在 deno.json 中使用 npm:honojsr:@hono/hono

¥Hono is available on both npm and JSR (the JavaScript Registry). You can use either npm:hono or jsr:@hono/hono in your deno.json:

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

使用第三方中间件时,你可能需要使用与中间件相同的注册表中的 Hono 来进行正确的 TypeScript 类型推断。例如,如果你使用 npm 中的中间件,则还应该使用 npm 中的 Hono:

¥When using third-party middleware, you may need to use Hono from the same registry as the middleware for proper TypeScript type inference. For example, if using the middleware from npm, you should also use Hono from npm:

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

我们还在 JSR 上提供了许多第三方中间件包。在 JSR 上使用中间件时,请使用 JSR 中的 Hono:

¥We also provide many third-party middleware packages on JSR. When using the middleware on JSR, use Hono from JSR:

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

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