Fastify for JavaScript (Node.js): 完整指南及示例
\n\n1. 什么是 Fastify 以及为什么需要它
\nFastify 是一个高性能的 Node.js Web 框架,受 Hapi 和 Express 启发,但专注于速度和低内存消耗。它由 NearForm 团队的开发者于 2016 年创建,此后成为用 JavaScript/TypeScript 构建 REST API、微服务和 Web 应用程序最快的解决方案之一。
\n使用 Fastify 的主要原因在于其性能。根据测试,在相同资源消耗下,它每秒能处理的请求数比 Express 多 30-40%。这得益于基于 Node.js streams 的异步架构、高效的 JSON 解析(通过 fast-json-stringify)以及基于 Radix Tree(压缩前缀树)的优化路由器。
除了速度,Fastify 还提供通过 JSON Schema 进行的内置模式验证、自动响应缓存、开箱即用的 TypeScript 支持、可扩展的插件系统以及出色的文档。这使其成为生产项目的理想选择,在这些项目中,稳定性和可预测的负载运行至关重要。
\n2. 安装
\nFastify 通过 npm(Node 包管理器)安装。请确保您已安装 Node.js 18 或更高版本(建议使用 LTS)。
\n# 基本安装\nnpm install fastify\n\n# 对于 TypeScript(可选)\nnpm install -D @types/node typescript\n\n# 用于处理 cookie、session 等\nnpm install @fastify/cookie @fastify/session\n如果您使用 yarn 或 pnpm:
\nyarn add fastify\n# 或\npnpm add fastify\n3. 快速入门 — 最小工作示例
\n创建一个文件 server.js 并通过 node server.js 运行它。
// server.js\nconst fastify = require('fastify')({\n logger: true // 启用内置日志记录器 (pino)\n});\n\n// 定义 GET / 路由\nfastify.get('/', async (request, reply) => {\n return { hello: 'world' };\n});\n\n// 启动服务器\nconst start = async () => {\n try {\n await fastify.listen({ port: 3000 });\n console.log('服务器已启动于 http://localhost:3000');\n } catch (err) {\n fastify.log.error(err);\n process.exit(1);\n }\n};\n\nstart();\n启动后,打开浏览器或执行 curl http://localhost:3000。您将收到 JSON 响应 {"hello":"world"}。
4. 主要方法/函数/类
\n\n4.1. fastify.get(path, options, handler)
\n签名: fastify.get(path: string, opts?: RouteShorthandOptions, handler: RequestHandler)
功能: 为指定路径的 HTTP GET 请求注册处理程序。
\nfastify.get('/user/:id', async (request, reply) => {\n const { id } = request.params;\n return { userId: id, name: 'John Doe' };\n});\n\n4.2. fastify.post(path, options, handler)
\n签名: fastify.post(path: string, opts?: RouteShorthandOptions, handler: RequestHandler)
功能: 为 HTTP POST 请求注册处理程序。自动解析请求体(JSON、form-data 等)。
\nfastify.post('/user', async (request, reply) => {\n const { name, email } = request.body;\n // 将用户保存到数据库...\n return { status: 'created', name, email };\n});\n\n4.3. fastify.register(plugin, opts)
\n签名:
图书馆中也有
推荐