Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS s3 listobjects with pagination

I want to implement pagination using aws s3. There are 500 files in object ms.files but i want to retrieve only 20 files at a time and next 20 next time and so on.

var params = {
  Bucket: 'mystore.in',
  Delimiter: '/',
  Prefix: '/s/ms.files/',
  Marker:'images',
};
s3.listObjects(params, function(err, data) {
  if (err) console.log(err, err.stack); 
  else     console.log(data);          
});
like image 917
Rohit Avatar asked Apr 19 '26 14:04

Rohit


1 Answers

Came across this while looking to list all of the objects at once, if your response is truncated it gives you a flag isTruncated = true and a continuationToken for the next call

If youre on es6 you could do this,

const AWS = require('aws-sdk');
const s3 = new AWS.S3({});

const listAllContents = async ({ Bucket, Prefix }) => {
  // repeatedly calling AWS list objects because it only returns 1000 objects
  let list = [];
  let shouldContinue = true;
  let nextContinuationToken = null;
  while (shouldContinue) {
    let res = await s3
      .listObjectsV2({
        Bucket,
        Prefix,
        ContinuationToken: nextContinuationToken || undefined,
      })
      .promise();
    list = [...list, ...res.Contents];

    if (!res.IsTruncated) {
      shouldContinue = false;
      nextContinuationToken = null;
    } else {
      nextContinuationToken = res.NextContinuationToken;
    }
  }
  return list;
};
like image 180
David Cheung Avatar answered Apr 21 '26 04:04

David Cheung