A bucket is a container that is used to store objects in Object Storage Service (OSS). Every object is contained in a bucket. This topic describes how to query the region of a bucket.
Prerequisites
Install the
ali-ossSDK.Configure the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables. The sample code obtains access credentials from these environment variables.
Example code
The following sample code shows how to query the region or location of a bucket:
const OSS = require('ali-oss');
const client = new OSS({
// Obtain the access credentials from environment variables. Before you run this code sample, make sure 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,
// Specify the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, specify oss-cn-hangzhou. Replace the example value with the actual region of your bucket.
region: 'oss-cn-hangzhou',
// Use the V4 signature algorithm.
authorizationV4: true,
// Specify the name of your bucket.
bucket: 'yourBucketName',
// Specify the public endpoint of the region where the bucket resides. For example, if the bucket is in the China (Hangzhou) region, specify https://oss-cn-hangzhou.aliyuncs.com. Replace the example value with the actual endpoint of your bucket.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});
async function getLocation() {
try {
const result = await client.getBucketInfo();
console.log(result.bucket.Location);
} catch (e) {
console.log(e);
}
}
getLocation();The sample outputs the value of the Location field, which indicates the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, the output is oss-cn-hangzhou.
References
For the complete sample code, see theGitHub example.
For more information about the API operation that is used in this sample, seeGetBucketLocation.