Tryliom
Tryliom

Reputation: 953

AWS S3 nodejs - How to get object by his prefix

I'm searching how check if an object exist in my aws s3 bucket in nodejs without list all my object (~1500) and check the prefix of the object but I cannot find how.

The format is like that:

<prefix I want to search>.<random string>/

Ex:

tutturuuu.dhbsfd7z63hd7833u/

Upvotes: 1

Views: 5333

Answers (1)

Renato Gama
Renato Gama

Reputation: 16599

Because you don't know the entire object Key, you will need to perform a list and filter by prefix. The AWS nodejs sdk provides such a method. Here is an example:

s3.listObjectsV2({
  Bucket: 'youBucket',
  MaxKeys: 1,
  Prefix: 'tutturuuu.'
}, function(err, data) {
  if (err) throw err;

  const objectExists = data.Contents.length > 0
  console.log(objectExists);
});

Note that it is important to use MaxKeys in order to reduce network usage. If more than one object has the prefix, then you will need to return everything and decide which one you need.

This API call will return metadata only. After you have the full key you can use getObject to retrieve the object contents.

Upvotes: 3

Related Questions