Skip to content
Advertisement

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?

Advertisement

Answer

You can use the following code:

// import 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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement