什么是 Fastify?
Fastify 是一个高度专注于以最少开销和强大的插件架构,为开发人员提供最佳体验的 Web 框架。
它受到了 Hapi
和 Express
的启发,是目前最快的 Node 框架之一。
Fastify
独特的将 JSON Schema
应用到请求时的 validation
和响应时的 serialization
, 作者写的 fast-json-stringify
包更是达到了2x faster than JSON.stringify的神奇效果。
为什么要使用 Fastify
- 100% 异步:框架的核心都是用
异步
代码实现的 - 高性能:每秒可以提供
34000
个请求 - 可扩展:Fastify 通过其
钩子
,插件
和装饰器
完全可扩展 - 基于模式:即使不是强制性的,我们建议使用
JSON Schema
来验证路由并序列化输出 - 日志记录:日志非常重要,但成本高昂,我们选择了最好的记录器
Pino
- 对开发者友好:该框架构建非常有表现力,不会牺牲性能和安全性
如何安装fastify?
使用 npm 安装:
npm i fastify --save
使用 yarn 安装:
yarn add fastify
脚手架安装
全局安装
npm i fastify-cli -g
进入目录
cd [myproject]
初始化Fastify脚手架
fastify generate
运行
npm start
如何创建一个简单的 Fastify 应用?
声明一个监听客户端http://127.0.0.1:3000/
的「GET」请求
Fastify返回 { hello: 'world' }
。
// 加载框架并新建实例const fastify = require('fastify')({ // 开始日志记录 logger: true})// 声明路由fastify.get('/', function(request, reply) { reply.send({ hello: 'world' })})// 启动服务!fastify.listen(3000, function(err, address) { if (err) { fastify.log.error(err) process.exit(1) } fastify.log.info(`server listening on ${address}`)})
-n-
我们还可以利用async/await
特性,讲Fastify进行异步操作
const fastify = require('fastify')()fastify.get('/', async (request, reply) => { return { hello: 'world' }})const start = async () => { try { await fastify.listen(3000) } catch (err) { fastify.log.error(err) process.exit(1) }}start()
就如同在 JavaScript 中一切皆为对象,在 Fastify 中,一切都是插件 (plugin)。
新建一个基础的插件
// my-first-pugin.jsasync function routes (fastify, options) { fastify.get('/', async (request, reply) => { return { hello: 'world' } })}module.exports = routes
在服务器上注册这个插件
const fastify = require('fastify')()// 注册插件fastify.register(require('./our-first-route'))// 监听3000端口号,启动fastify.listen(3000, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } fastify.log.info(`server listening on ${address}`)})
为了优化解析 JSON 与序列化 JSON 输出的过程,Fastify 可以序列化数据
我们可以在schema
的选项中设置 response
的值,能够加快 JSON 的序列化
约束200状态码的response的数据格式
const opts = { schema: { response: { 200: { type: 'object', properties: { hello: { type: 'string' } } } } }}fastify.get('/', opts, async (request, reply) => { return { hello: 'world' }})