En este tema se describe cómo listar todos los objetos de un bucket mediante el SDK de Object Storage Service (OSS) para Harmony.
Notas de uso
Para obtener información sobre las regiones y los endpoints compatibles con OSS, consulte Regions and endpoints.
Para listar objetos, necesita el permiso
oss:ListObjects. Para más información, consulte Attach a custom policy to a RAM user.
Código de ejemplo
A continuación se muestra un ejemplo de cómo llamar a la operación ListObjectsV2 para listar los objetos de un 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();