我设法读取了存储在 S3 存储桶中的 JSON 文件,但我必须进行大量我不完全理解的转换。
如果我们记录数据,我们会得到缓冲区数据的输出
s3.getObject(objParam, (err, data) => {
if (err) throw err;
console.log("🚀 ~ file: reader.js ~ line 31 ~ rs ~ data", data.Body)
});
// outputs data <Buffer 7b 0a 20 20 22 74 79 70 65 22 3a 20 22 42 75 66 66 ...
如果我们使用 toString('utf-8') 将上面的缓冲区转换为字符串,我会得到:
data.Body.toString('utf8')
// outputs:
{
"type": "Buffer",
"data": [
123,
34,
99,
115,
112,
45,
114,
101,
112,
111,
114,
....
我设法查看实际原始 JSON 的唯一方法是将上面的内容转换为 JSON,访问 data 属性,创建一个新的缓冲区,然后再次转换回 toString('utf-8')。
s3.getObject(objParam, (err, data) => {
if (err) throw err;
const jsonBytes = JSON.parse(data.Body.toString('utf-8'));
const buffer = Buffer.from(jsonBytes.data);
const bufferBackToString = buffer.toString('utf-8');
console.log("🚀 ~ file: reader.js ~ line 21 ~ s3.getObject ~ bufferBackToString", bufferBackToString);
});
// output: Logs my original JSON!
{
"myProperty": "myData"
} // or whatever...
如果它已经是一个缓冲区,为什么我必须转换为缓冲区并再次转换回字符串?缓冲区可以有不同的编码吗?
最佳答案
const getJsonFromS3 = async (filename, bucketName) => {
const s3Output = await s3.getObject({
Key: filename,
Bucket: bucketName
})
try {
const jsonString = await s3Output.Body?.transformToString()
const json = JSON.parse(jsonString ?? '')
return json
} catch (error) {
console.error('error parsing json', error)
return null
}
}
所有带有 data.toString('utf-8')
的建议都不适合我。
但使用 transformToString()
对我有用
关于javascript - 使用 Nodejs 读取存储在 aws S3 中的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67181138/