Reputation: 3057
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);
});
Upvotes: 10
Views: 29455
Reputation: 116
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;
}
Upvotes: 2
Reputation: 1688
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;
};
Upvotes: 19