Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if a bucket exists on AWS S3

How do I test if a bucket exists on AWS S3 using the aws-sdk?


This question is for testing if an object exists within a bucket: How to determine if object exists AWS S3 Node.JS sdk

This question is for Python: How can I check that a AWS S3 bucket exists?

like image 867
sdgfsdh Avatar asked Jun 13 '18 17:06

sdgfsdh


People also ask

Can we ping S3 bucket?

You cannot "ping a bucket" because bucket names are merely logical containers served by Amazon S3. There is no direct relationship between IP addresses and buckets.

How do I find my AWS S3 bucket?

Sign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/ . In the Buckets list, choose the name of the bucket that you want to view the properties for. Choose Properties. On the Properties page, you can configure the following properties for the bucket.


1 Answers

You can use the following code:

// import or require aws-sdk as AWS
// const AWS = require('aws-sdk');

const checkBucketExists = async bucket => { 
  const s3 = new AWS.S3();
  const options = {
    Bucket: bucket,
  };
  try {
    await s3.headBucket(options).promise();
    return true;
  } catch (error) {
    if (error.statusCode === 404) {
      return false;
    }
    throw error;
  }
};

The important thing is to realize that the error statusCode will be 404 if the bucket does not exist.

like image 148
sdgfsdh Avatar answered Sep 19 '22 23:09

sdgfsdh