為何選擇 Fastify?
有效率的伺服器意味著更低的基礎架構成本、在負載下更好的響應速度以及開心的使用者。您如何有效率地處理伺服器的資源,同時知道您在不犧牲安全性驗證和方便開發的情況下,盡可能地處理最多的請求?
這就是 Fastify 的用武之地。Fastify 是一個網頁框架,高度專注於提供最佳的開發人員體驗,具有最低的開銷和強大的插件架構。它的靈感來自 Hapi 和 Express,據我們所知,它是目前最快的網頁框架之一。
誰在使用 Fastify?
Fastify 很榮幸地為眾多組織和產品提供支援。
核心功能
以下是 Fastify 建構的主要功能和原則
- 高效能: 據我們所知,Fastify 是目前最快的網頁框架之一,根據程式碼的複雜程度,我們每秒可以處理高達 3 萬個請求。
- 可擴展: Fastify 可透過其鉤子、插件和裝飾器完全擴展。
- 基於 Schema: 即使它不是強制性的,我們仍然建議使用 JSON Schema 來驗證您的路由並序列化您的輸出,Fastify 內部會將 Schema 編譯成高效能的函數。
- 日誌記錄: 日誌非常重要但成本高昂;我們選擇了最好的日誌記錄器來幾乎消除這種成本,Pino!
- 開發人員友善: 該框架旨在非常具有表現力,並在不犧牲效能和安全性的情況下,幫助開發人員的日常使用。
- 支援 TypeScript: 我們努力維護 TypeScript 類型宣告檔案,以便我們能夠支援不斷成長的 TypeScript 社群。
快速開始
使用 NPM 取得 Fastify
npm install fastify
然後建立 server.js
並新增以下內容
- ESM
- CJS
// Import the framework and instantiate it
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
// Declare a route
fastify.get('/', async function handler (request, reply) {
return { hello: 'world' }
})
// Run the server!
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })
// Declare a route
fastify.get('/', function handler (request, reply) {
reply.send({ hello: 'world' })
})
// Run the server!
fastify.listen({ port: 3000 }, (err) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
最後,使用以下命令啟動伺服器
node server
並使用以下命令進行測試
curl https://127.0.0.1:3000
使用 CLI
取得 fastify-cli
以建立新的支架專案
npm install --global fastify-cli
fastify generate myproject
請求/響應驗證和鉤子
Fastify 可以做的不僅如此。例如,您可以使用 JSON Schema 輕鬆提供輸入和輸出驗證,並在執行處理常式之前執行特定操作
- ESM
- CJS
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
fastify.route({
method: 'GET',
url: '/',
schema: {
// request needs to have a querystring with a `name` parameter
querystring: {
type: 'object',
properties: {
name: { type: 'string'}
},
required: ['name'],
},
// the response needs to be an object with an `hello` property of type 'string'
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
},
// this function is executed for every request before the handler is executed
preHandler: async (request, reply) => {
// E.g. check authentication
},
handler: async (request, reply) => {
return { hello: 'world' }
}
})
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
const fastify = require('fastify')({ logger: true })
fastify.route({
method: 'GET',
url: '/',
schema: {
// request needs to have a querystring with a `name` parameter
querystring: {
type: 'object',
properties: {
name: { type: 'string'}
},
required: ['name'],
},
// the response needs to be an object with an `hello` property of type 'string'
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
},
// this function is executed for every request before the handler is executed
preHandler: (request, reply, done) => {
// E.g. check authentication
done()
},
handler: (request, reply) => {
reply.send({ hello: 'world' })
}
})
fastify.listen({ port: 3000 }, (err) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
TypeScript 支援
Fastify 附帶一個類型檔案,但您可能需要安裝 @types/node
,具體取決於您使用的 Node.js 版本。
以下範例會建立一個 http 伺服器。
我們傳遞所用 http 版本的相關類型。透過傳遞類型,我們可以正確地存取路由中底層的 http 物件。
如果使用 http2,我們將傳遞 <http2.Http2Server, http2.Http2ServerRequest, http2.Http2ServerResponse>
.
對於 https,請傳遞 http2.Http2SecureServer
或 http.SecureServer
而非 Server。
這可確保在伺服器處理常式中,我們也會取得 http.ServerResponse
,並在 reply.res
.
- 上具有正確的類型。
import Fastify, { FastifyInstance, RouteShorthandOptions } from 'fastify'
import { Server, IncomingMessage, ServerResponse } from 'http'
const server: FastifyInstance = Fastify({})
const opts: RouteShorthandOptions = {
schema: {
response: {
200: {
type: 'object',
properties: {
pong: {
type: 'string'
}
}
}
}
}
}
server.get('/ping', opts, async (request, reply) => {
return { pong: 'it worked!' }
})
const start = async () => {
try {
await server.listen({ port: 3000 })
const address = server.server.address()
const port = typeof address === 'string' ? address : address?.port
} catch (err) {
server.log.error(err)
process.exit(1)
}
}
start()
請造訪文件以深入了解 Fastify 提供的所有功能。
一個快速的網頁框架
憑藉我們在 Node.js 效能方面的經驗,Fastify 從頭開始建構,以達到 盡可能快。請查看我們的 效能基準部分,以比較 Fastify 與其他常見網頁框架的效能。
生態系統
Fastify 擁有一個不斷成長的插件生態系統。您的首選資料庫或範本語言可能已經有插件。請查看 生態系統頁面以瀏覽目前可用的插件。找不到您想要的插件嗎?沒問題, 撰寫一個插件非常容易!
認識團隊
依字母順序排列