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 |
|
Features supported by Fastify
-
High performance: Please see the table above.
-
Extensible: Achieve scalability through hooks, plugins and decorators.
-
Schema based: It is not mandatory to use JSON Schema Verify your routing configuration, configure it in time, and compile it easily Fast.
-
Logging: Use Pino to record logs and reduce losses.
-
Developer friendly: It is developer friendly, and it also considers and designs performance and security.
-
TypeScript ready: Support TypeScript
Fastify supports plugins
As of now, 48 Core plug-ins, 179 community plug-ins
So, how to use it?
Initialization
Create project
npm install --global fastify-cli
fastify generate myproject
Initialize project
npm init -y fastify
Installation dependencies
#npm
npm i fastify
#yarn
yarn add fastify
hello-world
##Return synchronously
// 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}
})
Asynchronous return
// 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}
})
How to use plugin
fastify.register(plugin, [options]), for more usage, you can click the link Similar to delivery, try jumping to the link~
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 教程!