node.js - NodeJS Stream 通过 async/await 返回错误

标签 node.js stream async-await

我正在尝试检查文件夹中是否存在图像。 如果它存在,我想将其流传输到 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/

相关文章:

Node.js - 以编程方式连接到 VPN 或通过 VPN 路由 HTTP 请求

javascript - npm run build 给出 npm ERR!代码生命周期

C# 函数返回一个 Stream

java - 在 JAVA 中使用 Lambda 的 AWS DynamoDB 触发器

c# - 从异步方法返回输出时推荐的方法签名?

linq - 带有 Select 的 Task.WhenAll 是一把枪——但为什么呢?

node.js - 在 Express 中有条件地提供静态文件的最佳方式是什么?

javascript - 黑客新闻 API - 获取最受欢迎的项目

c# - 如何安全地拦截自定义 Owin 中间件中的响应流

c# - 为什么 void async 不好?