Skip to content

Instantly share code, notes, and snippets.

@rahulrajaram
Created August 31, 2019 08:18
Show Gist options
  • Save rahulrajaram/f26f23c73b72209d65d9a57aca94a134 to your computer and use it in GitHub Desktop.
Save rahulrajaram/f26f23c73b72209d65d9a57aca94a134 to your computer and use it in GitHub Desktop.
List all S3 Objects using JavaScript SDK
/*
* File invokes s3#listObjects recursively to retrieve all objects
*/
const AWS = require('aws-sdk')
const s3 = new AWS.S3();
let args = {
'Bucket': ADD_BUCKET_NAME_HERE,
'Prefix': ADD_PATH_PREFIX_HERE_OR_REMOVE_THIS_ATTRIBUTE
};
function listObjects(allObjects, startingToken) {
if (startingToken !== undefined) {
args.ContinuationToken = startingToken;
}
const listObjectsPromise = s3.listObjectsV2(args).promise();
return listObjectsPromise.then((response) => {
if (response.NextContinuationToken) {
// Recursive call to retrieve further objects
return listObjects(allObjects, response.NextContinuationToken).then((results) => {
allObjects = allObjects || []
return allObjects.concat(results);
});
} else {
return response.Contents.map(item => item.Key);
}
}, (err) => {
console.log(err);
return []
});
}
listObjects().then((results) => {
console.log(results);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment