NodeJS 如何在javascript 3中获取s3桶中json文件

4xy9mtcn  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(165)

我已经有这个密码了

const express = require('express');
const { S3 } = require('@aws-sdk/client-s3');

const app = express();
const port = 3100;

const s3 = new S3({ region: 'us-west-2' });

app.get('/s3/sample', async (req, res) => {
  try {
    const params = {
      Bucket: `bucket`,
      Key: `category/file.json`,
      ContentType: "application/json",
    };

    s3.getObject(params, function(err, data) {
      if (err) {
        console.log(err, err.stack);
      } else {
        try {
          const json = JSON.parse(data.Body.toString('utf-8'));
          console.log(json);
        } catch (err) {
          console.log('Error parsing JSON:', err.message);
          console.log('JSON string:', data.Body.toString('utf-8'));
          console.log('data:', data);
        }
      }
    });

  } catch (error) {
    console.error(error);
    return {
      statusCode: 500,
      body: 'An error occurred while creating the table and inserting rows',
    };
  }
});

我一直收到[object Object]
已经试过ContentType: "application/json",了。
已尝试utf-8
也问chatgpt没有工作。
这是json文件

[
  {
    "imageThumbUrl": "",
    "imageUrl": "",
    "sku": "xxxx",
    "name": "xxxx",
    "price": 0,
    "allowedTransportModes": "xxxxx",
    "distributionPoints": "xxxxx",
    "availableForDeliveryFrom": "2021-01-15T00:00:00.000Z",
    "availableForDeliveryTo": "2024-05-24T00:00:00.000Z",
    "categories": ""
  }
]

我不知道为什么我一直得到对象对象。我试着研究,看起来我是一个经历这一切的人

e5nqia27

e5nqia271#

您不能只在Body上调用data.Body.toString(),因为Body的类型为Readable,如AWS JS SDK文档中所述
可以使用此函数从返回的Readable中获取完整的Body字符串:

const getReadableData = readable => {
  return new Promise((resolve, reject) => {
    const chunks = [];
    readable.once('error', (err) => reject(err));
    readable.on('data', (chunk) => chunks.push(chunk));
    readable.once('end', () => resolve(chunks.join('')));
  });
};

所以我们不用

const json = JSON.parse(data.Body.toString('utf-8'));
console.log(json);

使用

const promise = getReadableData(data.Body);
promise.then(value => {
  const decodedJson = JSON.parse(value);
  console.log(decodedJson);
});

相关问题