猿问

将 s3 对象数据放入数组 - 节点

我正在尝试从 S3 对象中获取数据并将其放入数组中。我计划通过这个数组映射并在网格/列表中的 React 前端显示数据。不过,我正在为嵌套函数而苦苦挣扎,因此我将不胜感激。


const dataFromS3 = async (bucket, file) => {

let lines = [];


const options = {

    Bucket: bucket,

    Key: file

  };


s3.getObject(options, (err, data) => {

if (err) {

  console.log(err);

} else {

  let objectData = data.Body.toString('utf-8');

  lines.push(objectData);

  console.log(lines);

  return lines;

}

  });

};

格式化有点奇怪,但这是我从 s3 获取数据的功能。我想以数组的形式获取此函数的输出并将其传递给我正在测试的“/”路由:


app.get('/', async (req, res, next) => {



try {

    let apolloKey = await dataFromS3(s3Bucket, apolloKeywords);

    res.send(apolloKey);

  } catch (err) {

    console.log('Error: ', err);

  }

});

似乎s3.getObject函数中的行的返回值需要在第一个函数中返回,以便我可以在 app.get 中访问它,但经过一些尝试后我似乎无法做到这一点。如果我在datafromS3()的末尾返回它,那么行中的值将变成一个空数组,并且我找不到返回它的方法。我也尝试使用此处找到的方法使用 Promise - How to get response from S3 getObject in Node.js? 但我得到一个 TypeError: Converting Circular Structure to JSON ...


白板的微信
浏览 159回答 1
1回答

jeck猫

你需要让你的 dataFromS3 像 htis 一样运行。你没有从中返回任何东西。AWS 还提供了基于 Promise 的功能。const dataFromS3 = async (bucket, file) => {  const lines = [];  const options = {    "Bucket": bucket,    "Key": file  };  const data = await s3.getObject(options).promise();  const objectData = data.Body.toString("utf-8");  lines.push(objectData); // You might need to conversion here using JSON.parse(objectData);  console.log(lines);  return lines;};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答