I've looked at some other posts and tried to replicate what they've done, but none of them seem to be running into the same issue I am. Basically, I'm trying to store the list of keys from a S3 bucket so I can iterate through them in my Vue app. I've got the code below, and you can see I have 3 console.log
statements where I'm trying to print the value of files
. The first one prints exactly what I expect it to, while the 2nd one prints []
, and the 3rd doesn't print at all. So for some reason it's not persisting the value of files
outside of the s3.listObjectsV2()
function, which means I can't access the actual files themselves in the app.
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();