您可以通过 Harmony SDK 的 headObject
接口判断对象是否存在。
判断对象是否存在前,您的账号必须具备 tos:GetObject
权限,具体操作请参见权限配置指南。
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: "Provide your ak", accessKeySecret: "Provide your sk", securityToken: 'Provide your securityToken', 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 Name:', error.name); 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 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); } } async function main() { try { const bucketName = 'node-sdk-test-bucket'; // 存储桶中的对象名 const objectKey = 'example_dir/example.txt'; const res = await client.headObject({ Bucket: bucketName, Key: objectKey, }); console.log('The object exists.'); console.log('headObject Request ID:', res.RequestId); } catch (error) { if (error instanceof TosServerError) { if (error.StatusCode === 404) { // 对象不存在 console.log(`The object doesn't exist`); return; } } handleError(error); } } main();
关于判断对象是否存在的 API 接口,请参见 HeadObject。