本篇文章給大家分享一個Nodejs web框架:Fastify,簡單介紹一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望對大家有所幫助!
前端的web框架,大部分都是建立在node基礎(chǔ)上的。fastify 也不例外。
前端web框架性能比對
如果真的是這樣的話,那么是很樂意去嘗試fastfy的 ??
Benchmarks
Machine: EX41S-SSD, Intel Core i7, 4Ghz, 64GB RAM, 4C/8T, SSD.
Method: : autocannon -c 100 -d 40 -p 10 localhost:3000
* 2, taking the second average
Framework | Version | Router? | Requests/sec |
---|---|---|---|
Express | 4.17.3 | ? | 14,200 |
hapi | 20.2.1 | ? | 42,284 |
Restify | 8.6.1 | ? | 50,363 |
Koa | 2.13.0 | ? | 54,272 |
Fastify | 4.0.0 | ? | 77,193 |
– | |||
http.Server |
16.14.2 | ? | 74,513 |
Fastify支持的特性
- 高性能: 請見上表.
- Extensible: 通過 hooks, plugins and decorators 來實現(xiàn)擴展性.
- Schema based: 不強制使用 JSON Schema 驗證你的路由配置,及時配置了,編譯也是很快的.
- Logging: 使用Pino來記錄日志,并把損耗降低。
- Developer friendly: 對開發(fā)者友好,而且對性能、安全性也有考慮、設(shè)計.
- TypeScript ready: 支持 TypeScript
Fastify支持的 plugins
截止到目前, 48個核心插件 、179個社區(qū)插件
那么,如何使用呢?
初始化
創(chuàng)建工程
npm install --global fastify-cli fastify generate myproject
初始化工程
npm init -y fastify
安裝依賴
#npm npm i fastify #yarn yarn add fastify
hello-world
同步返回
// ESM import Fastify from 'fastify' //const fastify = Fastify({ //logger: true //}) // CommonJs const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', (request, reply) => { reply.send({ hello: 'world' }) }) // Run the server! fastify.listen({ port: 3000 }, (err, address) => { if (err) throw err // Server is now listening on ${address} })
異步返回
// ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs //const fastify = require('fastify')({ //logger: true //}) fastify.get('/', async (request, reply) => { reply.type('application/json').code(200) return { hello: 'world' } }) fastify.listen({ port: 3000 }, (err, address) => { if (err) throw err // Server is now listening on ${address} })
plugin如何使用
fastify.register(plugin, [options]),