Este tópico descreve como listar todos os objetos em um bucket usando o SDK do Object Storage Service (OSS) para Harmony.
Notas de uso
Para obter informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regions and endpoints.
Para listar objetos, é necessário ter a permissão
oss:ListObjects. Para mais informações, consulte Attach a custom policy to a RAM user.
Código de exemplo
O código de exemplo a seguir mostra como chamar a operação ListObjectsV2 para listar objetos em um bucket:
import Client, { RequestError } from '@aliyun/oss';
// Create an OSSClient instance.
const client = new Client({
// Specify the AccessKey ID obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
// Specify the AccessKey secret obtained from STS.
accessKeySecret: 'yourAccessKeySecret',
// Specify the security token obtained from STS.
securityToken: 'yourSecurityToken',
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
});
/**
* List objects in a bucket.
* Use the listObjectsV2 method to list objects in the bucket and the metadata of the objects.
*/
const listObjectsV2 = async () => {
try {
// Use the listObjectsV2 method to list objects in the bucket and the metadata of the objects.
const res = await client.listObjectsV2({
bucket: 'yourBucketName', // Specify the name of the bucket.
});
// Display the objects and their metadata.
console.log(JSON.stringify(res));
} catch (err) {
// Capture the exceptions during the request.
if (err instanceof RequestError) {
// If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC.
console.log('code: ', err.code); // The error code.
console.log('message: ', err.message); // The error message.
console.log('requestId: ', err.requestId); // The request ID.
console.log('status: ', err.status); // The HTTP status code.
console.log('ec: ', err.ec); // The EC.
} else {
// Display other unknown types of errors.
console.log('unknown error: ', err);
}
}
};
// Call the listObjectsV2 function to list objects in the bucket.
listObjectsV2();