首页 > 解决方案 > 为什么从 S3 流创建的文件是空的?

问题描述

我正在尝试从 Cognito 识别的 lambda 函数访问私有 S3 存储桶中的文件。

我设法获得了一个预签名的 url 来下载文件。使用相同的参数,我尝试将读取流写入本地文件。创建了一个文件,但它是空的。我无法在此过程中发现任何错误。

const s3 = new AWS.S3({ apiVersion: 'latest' });
const file = 's3Filename.csv'
const userId = event.requestContext.identity.cognitoIdentityId;
const s3Params = {
    Bucket: 'MY_BUCKET',
    Key: `private/${userId}/${file}`, 
};

var fileStream = require('fs').createWriteStream('/path/to/my/file.csv'); 
var s3Stream = s3.getObject(s3Params).createReadStream();

// Try to print s3 stream errors
s3Stream
.on('error', function (err) {
    console.error(err); // prints nothing
});

// Try to print fs errors
s3Stream
.pipe(fileStream)
.on('error', function (err) {
    console.error('File Stream:', err); // prints nothing
})
.on('data', function (chunk) {
    console.log(chunk); // prints nothing
})
.on('end', function () {
    console.log('All the data in the file has been read'); // prints nothing
})
.on('close', function (err) {
    console.log('Stream has been Closed'); // prints nothing
});

我非常确信我的参数是正确的,因为我可以获得一个允许我下载文件的预签名 url。

console.log(s3.getSignedUrl('getObject', s3Params));

我还可以使用getObject().promise(). 这可以工作,但我正在解析一个 CSV 文件,我宁愿在内存上轻松一点并解析流。

try 
{
    const s3Response = await s3.getObject(s3Params).promise();
    let objectData = s3Response.Body.toString('utf-8'); 
    console.log(objectData);
}
catch (ex) 
{
    console.error(ex);
}

为什么从 S3 流创建的文件是空的?为什么没有打印出来的东西?

这可能是访问策略问题吗?如果是这样,为什么我在执行时没有收到任何错误?

标签: node.jsamazon-web-servicesamazon-s3aws-lambda

解决方案


推荐阅读