Hono vs Fastify
Hono(边缘优先,Cloudflare Workers)与 Fastify(Node.js 高性能)——现代 JS Web 框架对比。性能、边缘兼容性、生态系统。
Node 生态的默认选择:灵活、成熟、中间件库庞大
Schema 驱动、以性能为核心:每个路由都是一份契约
Fastify 官方(带"仅供参考"提示的)基准测试显示吞吐量领先 1.6 倍、延迟降低 1.7 倍,背后是 Schema 驱动的序列化和官方 OpenAPI 插件的支持。Express 5 的进步在于异步处理函数自动捕获错误。GitHub 上 Express 星标数遥遥领先(69,478 对 37,195)。新建的、对性能敏感的服务选 Fastify;已有 Express 代码库且团队熟悉 → 继续用 Express 5,官方没有提供迁移工具。
| 分类 | Express 5 | Fastify |
|---|---|---|
| 性能 | 6/10 | 9/10 |
| 学习难易度 | 9/10 | 7/10 |
| 生态系统 | 9/10 | 7/10 |
| 社区 | 10/10 | 7/10 |
| 就业市场 | 8/10 | 6/10 |
| 面向未来 | 7/10 | 8/10 |
// Express 5 - 异步路由处理函数 + 自动错误捕获
import express from 'express';
const app = express();
app.use(express.json());
// 简单的错误类 —— 用于在 API 边界给出有意义的错误信息
class NotFoundError extends Error {
status = 404;
}
async function getUser(id) {
const user = await db.users.findById(id);
if (!user) throw new NotFoundError('User not found');
return user;
}
// Express 5:异步处理函数 reject 或 throw 时会自动调用 next(err)。
// 别忘了 return 这个 Promise —— 否则 rejection 可能变成 unhandled。
app.get('/api/users/:id', async (req, res) => {
const user = await getUser(req.params.id);
res.json(user);
});
// 集中式错误中间件 —— 添加在全局栈的末尾
app.use((err, req, res, next) => {
const status = err.status ?? 500;
res.status(status).json({ error: err.message });
});
app.listen(3000, () => {
console.log('Express server listening on port 3000');
});// Fastify 5 - Schema 校验 + 自动序列化
import Fastify from 'fastify';
const fastify = Fastify({ logger: true });
// 响应 Schema:fast-json-stringify 会基于这个 Schema
// 编译出一个专用的序列化函数 —— 比通用的 JSON.stringify 更快。
const userSchema = {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
},
required: ['id', 'name', 'email'],
};
const getUserOpts = {
schema: {
params: {
type: 'object',
properties: { id: { type: 'string' } },
required: ['id'],
},
response: {
200: userSchema,
},
},
};
// 封装隔离:在这个插件内注册的 hook/decorator
// 只会渗透到这个 context 下的路由。
fastify.register(async function userRoutes(instance) {
instance.get('/api/users/:id', getUserOpts, async (request, reply) => {
const user = await db.users.findById(request.params.id);
if (!user) {
return reply.code(404).send({ error: 'User not found' });
}
request.log.info({ userId: user.id }, 'user fetched');
return user;
});
});
fastify.setErrorHandler((error, request, reply) => {
reply.status(error.statusCode ?? 500).send({ error: error.message });
});
await fastify.listen({ port: 3000 });Fastify 官方(带"仅供参考"提示的)基准测试显示吞吐量领先 1.6 倍、延迟降低 1.7 倍,背后是 Schema 驱动的序列化和官方 OpenAPI 插件的支持。Express 5 的进步在于异步处理函数自动捕获错误。GitHub 上 Express 星标数遥遥领先(69,478 对 37,195)。新建的、对性能敏感的服务选 Fastify;已有 Express 代码库且团队熟悉 → 继续用 Express 5,官方没有提供迁移工具。
获取免费咨询如果你要搭建一个新的、对性能敏感且需要 Schema 校验的服务,选 Fastify;如果已有 Express 投入且团队熟悉,选 Express 5。两者都在积极维护——npm registry 上 express@latest 是 5.2.1,fastify@latest 是 5.12.5(Fastify v6 处于 alpha 阶段,但稳定版仍是 5.x)——所以不要用"Express 已经过时"这种理由来做决定。如果你需要大量第三方中间件,天平会更倾向 Express。