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' } })