Last active
April 2, 2024 03:00
-
-
Save hmontazeri/e9493c2110d4640a5d10429ccbafb616 to your computer and use it in GitHub Desktop.
get more than 1000 elements from s3 bucket (node.js)
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
const AWS = require('aws-sdk'); | |
const s3 = new AWS.S3({ | |
region: 'eu-central-1', | |
accessKeyId: process.env.AWS_ACCESS_KEY_ID, | |
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, | |
}); | |
async function listAllObjectsFromS3Bucket(bucket, prefix) { | |
let isTruncated = true; | |
let marker; | |
const elements = []; | |
while(isTruncated) { | |
let params = { Bucket: bucket }; | |
if (prefix) params.Prefix = prefix; | |
if (marker) params.Marker = marker; | |
try { | |
const response = await s3.listObjects(params).promise(); | |
response.Contents.forEach(item => { | |
elements.push(item.Key); | |
}); | |
isTruncated = response.IsTruncated; | |
if (isTruncated) { | |
marker = response.Contents.slice(-1)[0].Key; | |
} | |
} catch(error) { | |
throw error; | |
} | |
} | |
return elements; | |
} | |
// example call | |
listAllObjectsFromS3Bucket('<your bucket name>', '<optional prefix>'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much, excellent code!