A bucket is a container used to store objects in Object Storage Service (OSS). Every object is contained in a bucket. This topic describes how to determine whether a bucket exists.
Sample code
The following code provides an example on how to determine whether a specific bucket exists:
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,
});
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()