繁体   English   中英

使用 Nodejs 读取存储在 aws S3 中的 JSON 文件

[英]Read JSON file stored in aws S3 with Nodejs

我设法读取了存储在我的 S3 存储桶中的 JSON 文件,但我不得不做很多我不完全理解的转换。

如果我们记录数据,我们会得到一个 output 的缓冲区数据

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,访问数据属性,创建一个新缓冲区,然后再次转换回 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 jsonBytes = JSON.parse(data.Body.toString('utf-8'));
console.log(jsonBytes);

为我工作,我确实在论坛上看到,s3.getObject 直接返回 json 而不是字符串

const getJsonFromS3 = async (filename, bucketName) => {
  const s3Output = await s3.getObject({
    Key: filename,
    Bucket: bucketName
  })

  const jsonString = await s3Output.Body?.transformToString()

  try {
    const json = JSON.parse(jsonString ?? '')
    return json
  } catch (error) {
    console.error('error parsing json', error)
    return null
  }
}

data.toString('utf-8')所有建议都不适合我。 但是使用transformToString()对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM