Skip to content

Node.js Fastify

Fastify 是高性能 Web 框架,速度远快于 Express,兼具插件架构和 JSON Schema 验证。

Fastify vs Express

FastifyExpress
性能~40,000 req/s~15,000 req/s
Schema 验证内置 JSON Schema需第三方库
插件系统核心自带app.use() 中间件
TypeScript原生支持@types/express

基础用法

bash
npm install fastify
js
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() 构建模块化应用
  • HooksonRequest / preHandler / onSend 等生命周期钩子