结合Koa写出流文件/图片到前端/浏览器

1
npm i fs-extra mime-types axios

读取本地文件写回前端

1
2
3
const localPath = path.join(__dirname, '../..', 'pic/not_found.png');
ctx.type = mime.lookup(localPath);
ctx.body = fs.readFileSync(localPath);

读取外部链接流文件写回前端

1
2
3
4
5
6
7
8
import mime from 'mime-types';

const response = await axios({
url,
responseType: 'stream',
});
ctx.type = mime.lookup(url);
ctx.body = response.data;

读取外部链接流文件并写入本地再返回前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import fsExtra from 'fs-extra';
import mime from 'mime-types';

const response = await axios({
url,
responseType: 'stream',
});
const filepath = path.join(__dirname, '../..', 'pic/not_found.png');
// 确保文件必须存在
await fsExtra.ensureDir(path.dirname(filepath));
await new Promise((resolve, reject) => {
const writer = fs.createWriteStream(filepath);
response.data.pipe(writer);
writer.on('finish', resolve);
writer.on('error', reject);
});
ctx.type = mime.lookup(filepath);
ctx.body = fs.createReadStream(filepath);