node.js koa-sendfile的使用方法
时间: 2024-05-03 10:22:08 浏览: 9
使用koa-sendfile可以很方便地将文件发送给客户端。以下是使用koa-sendfile的步骤:
1. 安装koa-sendfile
```
npm install koa-sendfile
```
2. 引入koa-sendfile
```
const sendfile = require('koa-sendfile');
```
3. 使用sendfile函数发送文件
```
router.get('/download', async (ctx, next) => {
const path = '/path/to/file';
await sendfile(ctx, path);
});
```
其中,第一个参数是koa的上下文对象,第二个参数是要发送的文件的路径。
4. 可选项
koa-sendfile还有一些可选项,可以根据需要设置:
- root:文件根目录,默认为当前工作目录。
- maxage:缓存时间,单位为毫秒,默认为0,表示不缓存。
- hidden:是否发送隐藏文件,默认为false。
- index:默认文件名,默认为'index.html'。
- gzip:是否开启gzip压缩,默认为true。
- brotli:是否开启brotli压缩,默认为false。
```
await sendfile(ctx, path, {
root: '/path/to/root',
maxage: 1000 * 60 * 60 * 24, // 1 day
hidden: true,
index: 'default.html',
gzip: false,
brotli: true
});
```