すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:バケット存在有無の確認

最終更新日:Nov 11, 2024

バケットは、オブジェクトをOSS (Object Storage Service) に格納するために使用されるコンテナーです。 このトピックでは、バケットが存在するかどうかを判断する方法について説明します。

サンプルコード

次のコードは、特定のバケットが存在するかどうかを判断する方法の例を示しています。

const OSS = require('ali-oss')
const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of your bucket.
  bucket: 'yourBucketName',
});

async function bucketisExist() {
  try {
    // Specify the name of the bucket. 
    const result = await client.getBucketInfo('Yourbucketname')
    console.log('bucketInfo: ', result.bucket)
  } catch (error) {
    // Determine whether the specified bucket exists. 
    if (error.name === 'NoSuchBucketError') {
      console.log('Bucket does not exist');
    } else {
      console.log(error)
    }
  }
}
bucketisExist()