分享一个Nodejs web框架:Fastify

本篇文章给大家分享一个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

Framework Version Router? Requests/sec

Express4.17.3✓14,200hapi20.2.1✓42,284Restify8.6.1✓50,363Koa2.13.0✗54,272Fastify4.0.077,193

http.Server16.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个社区插件

1.png

那么,如何使用呢?

初始化

创建工程

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]),更多的使用用法, 可以点击链接类似下发,跳转链接进尝试~

2.png

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的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2699521.html

(0)
上一篇 2025年3月7日 18:59:40
下一篇 2025年2月27日 07:40:21

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论