在 Web 开发中,经常需要提供静态文件服务,如图片、CSS、JavaScript 等。Fastify 是一个快速、低开销的 Web 框架,它提供了 fastify-static 插件来方便地提供静态文件服务。
安装 fastify-static
使用 npm 安装 fastify-static:
npm install fastify-static
使用 fastify-static
在 Fastify 应用程序中使用 fastify-static 插件,需要调用 register 方法并传入插件选项:
const fastify = require('fastify')();
fastify.register(require('fastify-static'), {
root: __dirname,
prefix: '/static/',
});其中:
root:静态文件根目录,此处使用__dirname表示当前文件所在目录。prefix:URL 前缀,此处使用/static/,表示所有静态文件的 URL 都以/static/开头。
示例代码
下面是一个完整的 Fastify 应用程序,提供了静态文件服务和一个简单的路由:
// www.javascriptcn.com code example
const fastify = require('fastify')();
// 注册 fastify-static 插件
fastify.register(require('fastify-static'), {
root: __dirname,
prefix: '/static/',
});
// 定义路由
fastify.get('/', async (request, reply) => {
return { message: 'Hello, world!' };
});
// 启动服务器
fastify.listen(3000, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening on ${address}`);
});在当前文件所在目录下创建一个 public 目录,并在其中创建一个 index.html 文件:
public/ └── index.html
在 index.html 文件中添加一些内容:
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is a static file served by Fastify.</p>
</body>
</html>启动服务器并访问 http://localhost:3000/static/index.html,即可看到 index.html 文件的内容。
总结
Fastify 的 fastify-static 插件提供了方便的静态文件服务,可以快速地为 Web 应用程序提供静态资源。在实际开发中,建议将静态文件与动态路由分离,以提高应用程序的可维护性和扩展性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/669083eedc1ed1a61b55d492