Node.js Fastify
Fastify 是高性能 Web 框架,速度远快于 Express,兼具插件架构和 JSON Schema 验证。
Fastify vs Express
| Fastify | Express | |
|---|---|---|
| 性能 | ~40,000 req/s | ~15,000 req/s |
| Schema 验证 | 内置 JSON Schema | 需第三方库 |
| 插件系统 | 核心自带 | app.use() 中间件 |
| TypeScript | 原生支持 | 需 @types/express |
基础用法
bash
npm install fastifyjs
import Fastify from 'fastify'
const fastify = Fastify({ logger: true })
// 路由 + JSON Schema 验证
fastify.get('/', {
schema: {
response: {
200: {
type: 'object',
properties: { hello: { type: 'string' } }
}
}
}
}, async (req, reply) => {
return { hello: 'world' }
})
await fastify.listen({ port: 3000 })路由参数 + 校验
js
fastify.get('/user/:id', {
schema: {
params: {
type: 'object',
properties: { id: { type: 'integer' } },
required: ['id']
}
}
}, async (req, reply) => {
return { userId: req.params.id }
})插件注册
js
// 注册路由插件
fastify.register(async (instance, opts) => {
instance.get('/api', async () => ({ api: 'v1' }))
}, { prefix: '/v1' })
// → /v1/api核心特性
- 高性能 — Node.js 最快 Web 框架之一
- JSON Schema — 请求/响应自动验证和序列化
- 插件式 —
register()构建模块化应用 - Hooks —
onRequest/preHandler/onSend等生命周期钩子