Fastify 是一个高度专一于以最少开销和强大的插件架构,为开发人员提供最佳体验的 Web 框架。git
它受到了 Hapi
和 Express
的启发,是目前最快的 Node 框架之一。github
Fastify
独特的将 JSON Schema
应用到请求时的 validation
和响应时的 serialization
, 做者写的 fast-json-stringify
包更是达到了2x faster than JSON.stringify的神奇效果。npm
异步
代码实现的34000
个请求钩子
,插件
和装饰器
彻底可扩展JSON Schema
来验证路由并序列化输出Pino
npm i fastify --save
yarn add fastify
npm i fastify-cli -g
cd [myproject]
fastify generate
npm start
声明一个监听客户端http://127.0.0.1:3000/
的「GET」请求json
Fastify返回 { hello: 'world' }
。api
// 加载框架并新建实例 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()
新建一个基础的插件服务器
// my-first-pugin.js async 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}`) })
咱们能够在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' } })