Fastify 是 Node.js 的一个快速且低开销的 Web 框架,它允许您轻松地构建高效的 Web 应用程序。其中一个常见的需求是将静态文件(例如 HTML、CSS 和 JavaScript 文件)与应用程序一起部署,本文将介绍如何在 Fastify 中实现此目标。
使用 fastify-static 插件
Fastify 框架已经提供了一个非常方便的插件 fastify-static,它是基于 fastify-static-cache 的二次封装。它允许我们将静态文件服务并部署到与应用程序相同的目录中。
安装
在使用 fastify-static 插件之前,我们需要通过 npm 进行安装:
npm install fastify-static
用例
下面是如何在 Fastify 中使用 fastify-static 插件:
// www.javascriptcn.com code example
const fastify = require('fastify')()
const path = require('path')
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'public'),
prefix: '/public/'
})
fastify.listen(3000, (err) => {
if (err) throw err
console.log('Server listening on http://localhost:3000')
})这里我们使用了 path 模块,通过 root 参数指定将要提供静态文件的目录位置。在这个例子中,我们已经将所有静态文件存储于 public 目录中。prefix 属性可用于添加路径前缀,以便快速为静态文件提供者添加前缀。
我们可以通过访问 http://localhost:3000/public/index.html 来返回 public 目录中的 index.html 文件。
缓存
fastify-static 插件使用了 etag 来进行文件内容的缓存。每当文件内容发生更改时,etag 将发生变化。因此,您不必担心在更新文件内容时需要手动清除缓存。
fastify-static 还支持文件的缓存使用时间,可以在 options 中添加 cacheControl 参数, 您可以使用这个参数来指定缓存的时间。例如:
// www.javascriptcn.com code example
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'public'),
prefix: '/public/',
cacheControl: true,
etag: true,
lastModified: true,
immutable: true,
maxAge: '1d'
})这里我们使用了 maxAge 属性来设置缓存过期时间(一天)。如果您不想让浏览器缓存某个文件,只需要将 maxAge 属性设置为 0。
手动处理静态资源
如果您不想依赖 fastify-static 插件,也可以使用 Node.js 自带的模块 http,来手工处理静态资源。下面是一个例子:
// www.javascriptcn.com code example
const http = require('http')
const path = require('path')
const fs = require('fs')
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'public', req.url)
const extname = path.extname(filePath)
const allowedExtentions = ['.html', '.css', '.js']
const contentType = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript'
}
if (allowedExtentions.includes(extname)) {
fs.readFile(filePath, (err, data) => {
if (err) throw err
res.writeHead(200, {'Content-Type': contentType[extname]})
res.write(data)
res.end()
})
} else {
res.writeHead(404)
res.end()
}
})
server.listen(3000, () => {
console.log('Server listening on http://localhost:3000')
})该代码片段将在 http://localhost:3000 上启动一个服务器并监听请求。当请求的URL与public目录中存在的文件名匹配时,服务器将返回该文件的内容和相应的Content-Type。
最后
以上两种方式都可以在 Fastify 中部署静态文件。Fastify提供的插件可轻松帮助您完成这项任务,但在某些情况下,您可能需要手动处理静态文件。无论哪种方法,您都可以使用规定的语法来创建快速且高效的服务器。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d6a447a941bf7134c6b988