我正在尝试检查文件夹中是否存在图像。 如果它存在,我想将其流传输到 res (我正在使用 Express) 如果它不存在,我想做另一件事。
我创建了一个异步函数,该函数应该返回图像的流(如果存在)或 false(如果不存在)。
当我这样做时,我得到了一个流,但浏览器上得到了无限的负载,就好像流有问题一样。
这是我可以得到的最小复制品: Link to runnable code
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
app.get('/', async (req, res) => {
// Check if the image is already converted by returning a stream or false
const ext = 'jpg';
const imageConvertedStream = await imageAlreadyConverted(
'./foo',
1,
'100x100',
80,
ext
);
// Image already converted, we send it back
if (imageConvertedStream) {
console.log('image exists');
res.type(`image/${ext}`);
imageConvertedStream.pipe(res);
return;
} else {
console.log('Image not found');
}
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
async function imageAlreadyConverted(
basePath,
id,
size,
quality,
extWanted
) {
return new Promise(resolve => {
// If we know the wanted extension, we check if it exists
let imagePath;
if (extWanted) {
imagePath = path.join(
basePath,
size,
`img_${id}_${quality}.${extWanted}`
);
} else {
imagePath = path.join(basePath, size, `img_${id}_${quality}.jpg`);
}
console.log(imagePath);
const readStream = fs.createReadStream(imagePath);
readStream.on('error', () => {
console.log('error');
resolve(false);
});
readStream.on('readable', () => {
console.log('readable');
resolve(readStream);
});
});
}
我的图像中有 95% 可用,并且我需要性能,我想检查 fs.stats 然后创建流比尝试创建流和处理错误花费的时间更长。
最佳答案
问题出在“可读”事件上。一旦我切换到“打开”事件,一切都很好。
关于node.js - NodeJS Stream 通过 async/await 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51259600/