How To Determine If A S3 Object Exists Using AWS SDK in Typescript
In this guide, we'll walk through using the AWS SDK to check if an object exists in an Amazon S3 bucket, with the help of promises and async/await, utilizing Typescript.
Code
import { S3 } from 'aws-sdk'; const s3 = new S3(); const bucket = "my-bucket"; const key = "my-key"; const checkIfExists = async (bucket: string, key: string) => { try { await s3.headObject({Bucket: bucket, Key: key}).promise(); return true; } catch(err) { console.log(err); return false; } }; checkIfExists(bucket, key).then(exists => console.log("Does object exist?: ", exists));
Detailed Code Explanation
Firstly, we import the S3 service object from the AWS SDK. Then, we initialize our S3 instance without passing any constructor.
We then define our checkIfExists function, which is a helper function to check if an object exists in the bucket.
Inside our checkIfExists
function, we use headObject
, which retrieves the metadata from an object without returning the object itself. This operation is useful if we're interested only in an object's metadata. If the object does not exist, AWS S3 returns a NotFound
error.
Then, we utilize promises and async/await to handle our requests
To conclude the function, we have a console log to verify the function's output.
Expected Output Format
The output format will be in boolean format, not JSON, as the result of the operation is either true (the object exists) or false (the object does not exist):
Does object exist?: true
or
Does object exist?: false
Considerations & Caveats
- This will only tell you if the object exists, not if your application can also perform actions, like reading or writing to the object. You might still need to confirm permissions on that object.
- If the bucket or object is not found, AWS S3 will return a
NotFound
error. Handle these errors appropriately in your code.
Required IAM Permissions and Example Policy
For this operation, you need the s3:GetObject
permission. An example IAM policy is:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*" } ] }
FAQ
1. Can I use this method to check for the existence of a bucket?
No, the headObject
method is specific to S3 objects. For buckets, use s3.headBucket
.
2. Does using headObject
incur costs?
Yes, it falls under the S3 standard request pricing.
3. What happens if the object is in a different AWS region?
The headObject
command works across all regions. You should specify the region while instantiating the S3 service object if it's different from the default region in your AWS configuration.
4. What if I don't have the s3:GetObject
permission?
AWS will deny the headObject
request and return an AccessDenied
error.