【问题标题】:s3.getObject(...).createReadStream is not a functions3.getObject(...).createReadStream 不是函数
【发布时间】:2021-08-03 22:06:20
【问题描述】:

我正在尝试使用我的 NodeJS 应用程序将文件从我的 s3 存储桶发送到客户端。这是我目前所拥有的:

import { S3 } from '@aws-sdk/client-s3';

const BUCKET_NAME = process.env.S3_BUCKET_NAME;

const s3 = new S3({
    region: 'ap-southeast-2',
    httpOptions: {
        connectTimeout: 2 * 1000,
        timeout: 60 * 1000,
    },
});

router.get('/download/:id', async (req, res) => {
    console.log('api: GET /download/:id');
    console.log('req.params.id: ', req.params.id);
    const result = await getRequiredInfo(req.params.id);
    if (typeof result !== 'number') {
        res.attachment(result.filename);
        await s3
            .getObject({
                Bucket: BUCKET_NAME,
                Key: result.location,
            })
            .createReadStream()
            .pipe(res);
    } else {
        res.sendStatus(result);
    }
});

当我运行这段代码时,我会收到:

(node:11224) UnhandledPromiseRejectionWarning: TypeError: s3.getObject(...).createReadStream is not a function

我想知道关于 SO 的问题,看起来其他人使用 getObject 和 createReadStream 的组合工作正常。在这一点上我有什么遗漏吗?我应该如何在响应中将文件作为流发送?

【问题讨论】:

  • @Rayon 我认为这不能解决我的问题。由于某种原因,错误出现在“.createReadStream()”行中,而在那个问题中,这个函数仍然被使用。
  • 我猜,s3.getObject 正在返回一个错误,这可能是错误的原因 createReadStream is not a function。添加错误处理程序并重试。
  • @Jishnu 感谢您的注意。实际上 getObject 工作正常,因为它返回文件名、正文等。该错误仅在我添加 createReadStream() 后发生。你能告诉我如何在管道(res)之前添加一个处理程序吗?

标签: javascript node.js amazon-web-services amazon-s3


【解决方案1】:

.createReadStream() 是 aws-sdk v2 中的一个方法。 @aws-sdk/client-s3 是 aws-sdk v3 的一部分。

要从 v3 获取流,您需要执行以下操作:

const response = await s3.getObject({
    Bucket: BUCKET_NAME,
    Key: key,
});

response.Body.pipe(res);

有关 aws-sdk v3 的更多信息:https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/

猜你喜欢
  • 2017-10-03
  • 2019-06-16
  • 2021-06-29
  • 2020-11-16
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2019-05-08
相关资源
最近更新 更多