-
-
Save rahulrajaram/f26f23c73b72209d65d9a57aca94a134 to your computer and use it in GitHub Desktop.
List all S3 Objects using JavaScript SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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