javascript - 将 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 ...
谢谢
解决方案
你需要让你的 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;
};
推荐阅读
- google-cloud-dataflow - Apache Beam:Python SDK 中的 DoFn.Setup 等效项
- html - 单击按钮会生成两个 GET 请愿书
- wordpress - 检测 Youtube 视频的进度以更改 Wordpress 页面的状态
- mysql - 不确定如何为上述任务构建 SQL 查询
- javascript - Parsley.js:如何制作一个现有验证器的自定义验证器
- java - 矩阵商店。我们要去哪里?
- python - 如何获得给定 2 个数组的随机样本?
- linux - 简单备份脚本的进度条
- shell - 从 ansible 运行 sed 命令
- laravel - 为什么可以从所有命名空间访问 laravel 助手?