How do I test if a bucket exists on AWS S3

妖精的绣舞 提交于 2019-12-20 00:51:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50842835/how-do-i-test-if-a-bucket-exists-on-aws-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!