How do I test if a bucket exists on AWS S3

前端 未结 2 1601
花落未央
花落未央 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 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.

提交回复
热议问题