Check if a bucket exists (Node.js SDK)
Updated at:
A bucket is a container used to store objects in Object Storage Service (OSS). This topic describes how to determine whether a bucket exists.
Sample code
The following code checks if a specified bucket exists.
const OSS = require('ali-oss')
const client = new OSS({
// Set region to the region where your bucket is located. For example, if your bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before running this code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Set yourBucketName to the name of your bucket.
bucket: 'yourBucketName',
});
async function bucketisExist() {
try {
// Specify the bucket name.
const result = await client.getBucketInfo('Yourbucketname')
console.log('bucketInfo: ', result.bucket)
} catch (error) {
// Check if the specified bucket exists.
if (error.name === 'NoSuchBucketError') {
console.log('Bucket does not exist');
} else {
console.log(error)
}
}
}
bucketisExist()
Is this page helpful?