AWS s3 listobjects with pagination

24.9k views Asked by At

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);          
});
3

There are 3 answers

1
Rohit On

Solution as shared by Mr Jarmod :

var params = {
  Bucket: 'mystore.in',
  Delimiter: '/',
  Prefix: '/s/ms.files/',
  Marker:'',
  MaxKeys : 20
};
s3.listObjects(params, function(err, data) {
  if (err) console.log(err, err.stack); 
  else     console.log(data);          
});
0
caaatisgood On

For anyone who is using @aws-sdk/client-s3 and TypeScript, here's an example of pulling all objects from a bucket:

import {
  S3Client,
  ListObjectsV2Command,
  ListObjectsV2CommandInput,
  _Object,
} from "@aws-sdk/client-s3";

export const fetchObjects = async (bucket: string) => {
  const objects: _Object[] = [];

  async function fetchObjectsWithPagination(
    bucket: string,
    continuationToken?: ListObjectsV2CommandInput["ContinuationToken"]
  ): Promise<void> {
    const s3 = new S3Client({ region: "YOUR_S3_BUCKET_REGION" });
  
    const result = await s3.send(
      new ListObjectsV2Command({
        Bucket: bucket,
        ContinuationToken: continuationToken,
      })
    );

    objects.push(...(result.Contents || []));
  
    if (result.NextContinuationToken) {
      return fetchObjectsWithPagination(bucket, result.NextContinuationToken);
    }

    return;
  }

  await fetchObjectsWithPagination(bucket);

  return objects;
}
2
David Cheung On

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;
};