我是靠谱客的博主 粗犷老师,这篇文章主要介绍分享一个Nodejs web框架:Fastify,现在分享给大家,希望可以做个参考。

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

前端的web框架,大部分都是建立在node基础上的。fastify 也不例外。

前端web框架性能比对

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

FrameworkVersionRouter?Requests/sec
Express4.17.314,200
hapi20.2.142,284
Restify8.6.150,363
Koa2.13.054,272
Fastify4.0.077,193
-


http.Server16.14.274,513

Fastify支持的特性

  • 高性能: 请见上表.
  • Extensible: 通过 hooks, plugins and decorators 来实现扩展性.
  • Schema based: 不强制使用 JSON Schema 验证你的路由配置,及时配置了,编译也是很快的.
  • Logging: 使用Pino来记录日志,并把损耗降低。
  • Developer friendly: 对开发者友好,而且对性能、安全性也有考虑、设计.
  • TypeScript ready: 支持 TypeScript

Fastify支持的 plugins

1.png

那么,如何使用呢?

初始化

创建工程

复制代码
1
2
npm install --global fastify-cli fastify generate myproject
登录后复制

初始化工程

复制代码
1
npm init -y fastify
登录后复制

安装依赖

复制代码
1
2
3
4
5
#npm npm i fastify #yarn yarn add fastify
登录后复制

hello-world

同步返回

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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} })
登录后复制

异步返回

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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如何使用

2.png

复制代码
1
2
3
4
5
6
7
8
const fastifySession = require('fastify-session') fastify.register(fastifySession, { cookieName: 'sessionId', secret: 'a secret with minimum length of 32 characters', cookie: { secure: false }, expires: 1800000 })
登录后复制

更多使用

  • Example List
  • Getting Started
  • Guides
  • Server
  • Routes
  • Encapsulation
  • Logging
  • Middleware
  • Hooks
  • Decorators
  • Validation and Serialization
  • Fluent Schema
  • Lifecycle
  • Reply
  • Request
  • Errors
  • Content Type Parser
  • Plugins
  • Testing
  • Benchmarking
  • How to write a good plugin
  • Plugins Guide
  • HTTP2
  • Long Term Support
  • TypeScript and types support
  • Serverless
  • Recommendations

相关link

  • #json schema

  • #pino

最后

以上就是粗犷老师最近收集整理的关于分享一个Nodejs web框架:Fastify的全部内容,更多相关分享一个Nodejs内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部