【发布时间】:2022-01-01 03:38:51
【问题描述】:
我正在尝试将 Express 端点从 aws-sdk for JavaScript 的 v2 迁移到 v3。端点是 AWS S3 的文件下载器。
在版本 2 中,我将GetObject 的结果以可读流的形式传回浏览器。在版本 3 中,同样的技术失败并出现错误:
TypeError: data.Body.createReadStream 不是函数
如何处理从新 GetObjectCommand 返回的数据?它是一个斑点吗?我很难在v3 SDK docs 中找到任何有用的东西。
这是端点的两个版本:
import AWS from 'aws-sdk'
import dotenv from 'dotenv'
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
dotenv.config()
// VERSION 3 DOWNLOADER - FAILS
const getFileFromS3v3 = async (req, res) => {
const client = new S3Client({ region: 'us-west-2' })
const params = {
Bucket: process.env.AWS_BUCKET,
Key: 'Tired.pdf',
}
const command = new GetObjectCommand(params)
try {
const data = await client.send(command)
console.log(data)
data.Body.createReadStream().pipe(res)
} catch (error) {
console.log(error)
}
}
// VERSION 2 DOWNLOADER - WORKS
const getFileFromS3 = async (req, res) => {
const filename = req.query.filename
var s3 = new AWS.S3()
var s3Params = {
Bucket: process.env.AWS_BUCKET,
Key: 'Tired.pdf',
}
// if the file header exists, stream the file to the response
s3.headObject(s3Params, (err) => {
if (err && err.code === 'NotFound') {
console.log('File not found: ' + filename)
} else {
s3.getObject(s3Params).createReadStream().pipe(res)
}
})
}
export { getFileFromS3, getFileFromS3v3 }
【问题讨论】:
标签: amazon-web-services express amazon-s3 aws-sdk