本篇文章给大家分享一个nodejs web框架:fastify,简单介绍一下fastify支持的特性、fastify支持的插件以及fastify的使用方法,希望对大家有所帮助!
前端的web框架,大部分都是建立在node基础上的。fastify 也不例外。
前端web框架性能比对如果真的是这样的话,那么是很乐意去尝试fastfy的 ??
benchmarksmachine: 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
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 来实现扩展性.schema based: 不强制使用 json schema 验证你的路由配置,及时配置了,编译也是很快的.logging: 使用pino来记录日志,并把损耗降低。developer friendly: 对开发者友好,而且对性能、安全性也有考虑、设计.typescript ready: 支持 typescript fastify支持的 plugins截止到目前, 48个核心插件 、179个社区插件
那么,如何使用呢?初始化创建工程
npm install --global fastify-clifastify generate myproject
初始化工程
npm init -y fastify
安装依赖
#npm npm i fastify#yarn yarn add fastify
hello-world同步返回
// esmimport fastify from 'fastify'//const fastify = fastify({ //logger: true//})// commonjsconst fastify = require('fastify')({ logger: true})// declare a routefastify.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}})
异步返回
// esmimport 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]),更多的使用用法, 可以点击链接类似下发,跳转链接进尝试~
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 listgetting startedguidesserverroutesencapsulationloggingmiddlewarehooksdecoratorsvalidation and serializationfluent schemalifecyclereplyrequesterrorscontent type parserpluginstestingbenchmarkinghow to write a good pluginplugins guidehttp2long term supporttypescript and types supportserverlessrecommendations相关link#json schema
#pino
更多node相关知识,请访问:nodejs 教程!
以上就是分享一个nodejs web框架:fastify的详细内容。