我正在尝试从 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函数中lines的返回值,以便我可以在app.get中访问它,但是经过一番尝试后我似乎无法做到。如果我在 datafromS3() 末尾返回它,并且我找不到返回它的方法,则 rows 中的值将变成空数组。我尝试使用 promise 也使用这里找到的方法 - How to get response from S3 getObject in Node.js?但我收到 TypeError: Converting Circular Structure to JSON...
谢谢
最佳答案
您需要使 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;
};
关于javascript - 将 s3 对象数据放入数组 - Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616008/