17

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?

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

3 Answers3

31

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.

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • can you explain why you add the `.promise()` chain? the aws docs use a pretty simple example different than yours. i might not be seeing something that you do. https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headBucket-property – nsun Jun 05 '19 at 17:26
  • 1
    `.promise()` enables the use of `async` / `await` – sdgfsdh Jun 05 '19 at 17:28
  • I'm getting a 400 Bad request when I try this with aws-sdk 2.484.0, IF the bucket has existed before. With a bucket name that I've never created, the code works – Daniel Persson Jun 30 '19 at 13:42
9

Looks like after this change from aws-sdk v2 to v3 you can't do it with headBucket().

For those who are using v3 you could give this a shot:

const { S3Client, HeadBucketCommand } = require('@aws-sdk/client-s3');

const checkBucketExists = async (bucket) => {
    const client = new S3Client();
    const options = {
        Bucket: bucket,
    };

    try {
        await client.send(new HeadBucketCommand(options));
        return true;
    } catch (error) {
        if (error["$metadata"].httpStatusCode === 404) {
            return false;
        }
        throw error;
    }
}
chridam
  • 100,957
  • 23
  • 236
  • 235
Aaron Kauffman
  • 103
  • 1
  • 5
  • 1
    I found that the error object that is returned on the catch has a different path to the http status code. `error["$metadata"].httpStatusCode` – Jeremy Richardson Mar 18 '22 at 18:26
4

To test if a bucket exists, you check the statusCode attribute from your createBucket callback method. If it is 409, then it has been created before. I hope this is clear enough?

const ID = ''//Your access key id
const SECRET = ''//Your AWS secret access key

const BUCKET_NAME = ''//Put your bucket name here

const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
})

const params = {
    Bucket: BUCKET_NAME,
    CreateBucketConfiguration: {
        // Set your region here
        LocationConstraint: "eu-west-1"
    }
}
s3.createBucket(params, function(err, data) {
   if (err && err.statusCode == 409){
    console.log("Bucket has been created already");
   }else{
       console.log('Bucket Created Successfully', data.Location)
   }
})
2mighty
  • 149
  • 2
  • 5
  • 2
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the questions. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Apr 26 '20 at 13:49