After researching various tutorials and examples, I attempted to replicate their implementations without success. My current issue involves storing a list of keys from an S3 bucket in order to iterate through them within my Vue application. In the code snippet provided, there are 3 console.log
statements that attempt to display the value of files
. Surprisingly, the first log outputs the expected result, while the second one displays []
, and the third does not print anything at all. This inconsistency suggests that the value of files
is not persisting outside the s3.listObjectsV2()
function, thereby hindering access to the actual files in the app itself.
let AWS = require("aws-sdk");
AWS.config.update({
accessKeyId: process.env.VUE_APP_ACCESS_KEY,
secretAccessKey: process.env.VUE_APP_ACCESS_KEY,
region: "us-east-1",
});
let s3 = new AWS.S3();
let params = {
Bucket: "my-bucket",
Delimiter: "",
};
let getS3Files = () => {
let files = [];
s3.listObjectsV2(params, function (err, data) {
if (data) {
data.Contents.forEach((file) => {
files.push({
fileName: file.Key,
fileDate: file.LastModified,
});
});
console.log(files);
}
});
console.log(files);
if (files.length > 0) {
files = files.sort((a, b) => b.fileDate - a.fileDate);
console.log(files);
}
return files;
};
getS3Files();