OSS does not provide a dedicated method to check bucket existence. Instead, call getBucketInfo and inspect the error: if the error name is NoSuchBucketError, the bucket does not exist. A successful response means the bucket exists.
Prerequisites
Before you run the sample code, ensure that you have:
Installed the
ali-ossNode.js SDKSet the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables
Sample code
The following code checks whether 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()该文章对您有帮助吗?