简介

Fastify是一个类似于 ExpressJS的Web 服务器框架,但具有更好的性能

image.png

生态系统非常完善,有很多现成的插件。但是在第一个测试中,我只用了了fastify-static插件来获取 .html 文件

示例

初始化项目

首先,创建一个void文件夹并安装Fastify和fastify-static

npm i fastify fastify-static

app.js

创建一个app.js,它是你的根文件
你可以编写这个文件的基础来创建一个新的 Fastify 服务器

const path = require("path")
const f = require('fastify')({logger: false})

f.register(require('fastify-static'), {
    root: path.join(__dirname, 'public'),
    prefix: '/public/',
})

// In this example, when you get localhost:3000, ou have the time
f.get('/', (request, reply) => {
    reply.header('Content-Type', 'application/json')
    reply.send({hello: new Date()})
})
f.get('/about', (request, reply) => {
    reply.sendFile('about.html' )
})


const start = async () => {
    try {
        await f.listen(3000)
    } catch (err) {
        f.log.error(err)
        process.exit(1)
    }
}
start().then(r => r)

HTML

创建一个/public文件夹和一个about.html文件

image.png

启动

npm start
点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部