首頁  >  文章  >  web前端  >  分享一個Nodejs web框架:Fastify

分享一個Nodejs web框架:Fastify

青灯夜游
青灯夜游轉載
2022-08-04 21:23:152698瀏覽

這篇文章跟大家分享一個Nodejs web框架:Fastify,簡單介紹一下Fastify支援的特性、Fastify支援的外掛程式以及Fastify的使用方法,希望對大家有幫助!

分享一個Nodejs web框架:Fastify

前端的web框架,大部分都是建立在node基礎上的。 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

##FrameworkVersionRouter?Requests/secExpress4.17.3✓14,200hapi ✓8.6.1✗Fastify#77,193
#20.2.142,284 Restify##✓50,363
#Koa 2.13.0

54,272

#4.0.0
######## ##-##########################################http.Server## #######16.14.2######✗######74,513############

Fastify支援的功能

  • 高效能:  請見上表.
  • Extensible:透過hooks, plugins and decorators 實現擴展性.
  • Schema based:  不強制使用 JSON Schema 驗證你的路由配置,及時配置了,編譯也是很及時快的.
  • Logging:  使用Pino來記錄日誌,並且降低損耗。
  • Developer friendly:  對開發者友好,而且對效能、安全性也有考慮、設計.
  • TypeScript ready: 支援  TypeScript 

Fastify支援的 #plugins

##截止到目前,48個核心外掛、179個社群外掛程式

分享一個Nodejs web框架:Fastify

那麼,要如何使用呢?

初始化

建立工程

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]),更多的使用用法,可以點擊鏈接類似下發,跳到連結進嘗試~

分享一個Nodejs web框架:Fastify

const fastifySession = require('fastify-session')

fastify.register(fastifySession, {
    cookieName: 'sessionId',
    secret: 'a secret with minimum length of 32 characters',
    cookie: { secure: false },
    expires: 1800000
})

更多使用

相关link

更多node相关知识,请访问:nodejs 教程

以上是分享一個Nodejs web框架:Fastify的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除