跳到主要内容

最小服务与心智模型

在 Node.js 上起一个 Hono 服务最少要什么?​

  • 依赖: hono + @hono/node-server; Node 20 及以上;
  • 脚手架: npm create hono@latest my-app -- --template nodejs;
  • 注意: -- 必须带, 参数才会透传;
  • 三份文件: package.json、tsconfig.json、src/index.ts;
package.json
{
"type": "module",
"scripts": { "dev": "tsx watch src/index.ts", "build": "tsc", "start": "node dist/index.js" },
"dependencies": { "hono": "^4", "@hono/node-server": "^2" },
"devDependencies": { "typescript": "^5", "tsx": "^4", "@types/node": "^22" }
}

Hono 最小服务怎么写?​

import { serve } from "@hono/node-server";
import { Hono } from "hono";

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

serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 3000) }, (info) => {
console.log(`http://localhost:${info.port}`);
});
  • 基本用法: serve({ fetch: app.fetch, port, hostname });
  • 默认: port 是 3000, serve(app) 是简写;
  • 返回原生 node:http server, 关闭由应用负责, 见 009;

serve 还有哪些选项?​

  • 其他选项: serverOptions 与 websocket;
  • 换协议: createServer 可换成 node:https 或 node:http2;
  • 容器里 hostname: "0.0.0.0", 端口走环境变量;