How do I test if a bucket exists on AWS S3

前端 未结 2 1582
花落未央
花落未央 2021-01-12 06:06

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 exis

相关标签:
2条回答
  • 2021-01-12 06:58

    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)
       }
    })
    
    0 讨论(0)
  • 2021-01-12 07:07

    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.

    0 讨论(0)
提交回复
热议问题