Skip to content

Node.js

Node.js 是一个开源的跨平台 JavaScript 运行时环境。

¥Node.js is an open-source, cross-platform JavaScript runtime environment.

Hono 最初并不是为 Node.js 设计的。但使用 Node.js 适配器 它也可以在 Node.js 上运行。

¥Hono was not designed for Node.js at first. But with a Node.js Adapter it can run on Node.js as well.

信息

它适用于大于 18.x 的 Node.js 版本。具体所需的 Node.js 版本如下:

¥It works on Node.js versions greater than 18.x. The specific required Node.js versions are as follows:

  • 18.x => 18.14.1+

  • 19.x => 19.7.0+

  • 20.x => 20.0.0+

本质上,你可以简单地使用每个主要版本的最新版本。

¥Essentially, you can simply use the latest version of each major release.

1. 设置

¥ Setup

Node.js 的启动器可用。使用 "create-hono" 命令启动你的项目。为此示例选择 nodejs 模板。

¥A starter for Node.js is available. Start your project with "create-hono" command. Select nodejs template for this example.

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono my-app

移至 my-app 并安装依赖。

¥Move to my-app and install the dependencies.

sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i

2. Hello World

编辑 src/index.ts

¥Edit src/index.ts:

ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Node.js!'))

serve(app)

3. 运行

¥ Run

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

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

sh
npm run dev
sh
yarn dev
sh
pnpm dev

更改端口编号

¥Change port number

你可以使用 port 选项指定端口号。

¥You can specify the port number with the port option.

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

访问原始 Node.js API

¥Access the raw Node.js APIs

你可以从 c.env.incomingc.env.outgoing 访问 Node.js API。

¥You can access the Node.js APIs from c.env.incoming and c.env.outgoing.

ts
import { Hono } from 'hono'
import { serve, type HttpBindings } from '@hono/node-server'
// or `Http2Bindings` if you use HTTP2

type Bindings = HttpBindings & {
  /* ... */
}

const app = new Hono<{ Bindings: Bindings }>()

app.get('/', (c) => {
  return c.json({
    remoteAddress: c.env.incoming.socket.remoteAddress,
  })
})

serve(app)

提供静态文件

¥Serve static files

你可以使用 serveStatic 从本地文件系统提供静态文件。例如,假设目录结构如下:

¥You can use serveStatic to serve static files from the local file system. For example, suppose the directory structure is as follows:

sh
./
├── favicon.ico
├── index.ts
└── static
    ├── hello.txt
    └── image.png

如果访问路径 /static/* 并返回 ./static 下的文件,你可以编写以下内容:

¥If access to the path /static/* comes in and returns a file under ./static, you can write the following:

ts
import { serveStatic } from '@hono/node-server/serve-static'

app.use('/static/*', serveStatic({ root: './' }))

使用 path 选项在目录根中提供 favicon.ico

¥Use the path option to serve favicon.ico in the directory root:

ts
app.use('/favicon.ico', serveStatic({ path: './favicon.ico' }))

如果访问路径 /hello.txt/image.png 并返回名为 ./static/hello.txt./static/image.png 的文件,你可以使用以下内容:

¥If access comes to the path /hello.txt or /image.png and returns a file named ./static/hello.txt or ./static/image.png, you can use the following:

ts
app.use('*', serveStatic({ root: './static' }))

rewriteRequestPath

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

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

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

http2

你可以在 Node.js http2 服务器 上运行 hono。

¥You can run hono on a Node.js http2 Server.

未加密 http2

¥unencrypted http2

ts
import { createServer } from 'node:http2'

const server = serve({
  fetch: app.fetch,
  createServer,
})

加密 http2

¥encrypted http2

ts
import { createSecureServer } from 'node:http2'
import { readFileSync } from 'node:fs'

const server = serve({
  fetch: app.fetch,
  createServer: createSecureServer,
  serverOptions: {
    key: readFileSync('localhost-privkey.pem'),
    cert: readFileSync('localhost-cert.pem'),
  },
})

构建和部署

¥Building & Deployment

完成以下步骤以构建一个简单的 Hono 应用。具有前端框架的应用可能需要使用 Hono 的 Vite 插件

¥Complete the following steps to build a simple Hono app. Apps with a front-end framework may need to use Hono's Vite plugins.

  1. "outDir": "./dist" 添加到 tsconfig.jsoncompilerOptions 部分。

    ¥Add "outDir": "./dist" to the compilerOptions section tsconfig.json.

  2. "exclude": ["node_modules"] 添加到 tsconfig.json

    ¥Add "exclude": ["node_modules"] to tsconfig.json.

  3. "build": "tsc" 添加到 package.jsonscript 部分。

    ¥Add "build": "tsc" to script section of package.json.

  4. 运行 npm install typescript --save-dev

    ¥Run npm install typescript --save-dev.

  5. "type": "module" 添加到 package.json

    ¥Add "type": "module" to package.json.

  6. 运行 npm run build

    ¥Run npm run build!

Dockerfile

以下是 Dockerfile 的示例。你必须完成上述步骤 1-5,此构建和部署过程才能工作。

¥Here is an example of a Dockerfile. You must complete steps 1-5 above before this build and deployment process will work.

Dockerfile
FROM node:20-alpine AS base

FROM base AS builder

RUN apk add --no-cache gcompat
WORKDIR /app

COPY package*json tsconfig.json src ./

RUN npm ci && \
    npm run build && \
    npm prune --production

FROM base AS runner
WORKDIR /app

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 hono

COPY --from=builder --chown=hono:nodejs /app/node_modules /app/node_modules
COPY --from=builder --chown=hono:nodejs /app/dist /app/dist
COPY --from=builder --chown=hono:nodejs /app/package.json /app/package.json

USER hono
EXPOSE 3000

CMD ["node", "/app/dist/index.js"]

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