通过 HeadBucket 获取存储桶(Bucket)的信息, 同时可以根据返回的 err 中的 HTTP Code 信息,判断桶是否存在。本文介绍如何获取桶元数据和判断桶是否存在。
tos:HeadBucket
权限。具体操作,请参见权限配置指南。// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } const bucketName = 'node-sdk-test-bucket-not-exist'; async function main() { try { // 判断桶是否存在 const { data } = await client.headBucket(bucketName); console.log(`the region of ${bucketName} is`, data['x-tos-bucket-region']); console.log(`the storageClass of ${bucketName} is`, data['x-tos-storage-class']); } catch (error) { if (error instanceof TosServerError) { if (error.statusCode === 404) { // 存储桶不存在 console.log('Bucket not found.'); return; } } handleError(error); } } main();
// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } const bucketName = 'node-sdk-test-bucket'; async function main() { try { // 获取桶元数据信息 const { data } = await client.headBucket(bucketName); console.log(`the region of ${bucketName} is`, data['x-tos-bucket-region']); console.log(`the storageClass of ${bucketName} is`, data['x-tos-storage-class']); } catch (error) { handleError(error); } } main();