List objects (Harmony SDK)
Updated at:
This topic describes how to list all objects in a bucket using the Object Storage Service (OSS) SDK for Harmony.
Usage notes
-
For information about the regions and endpoints that are supported by OSS, see Regions and endpoints.
-
To list objects, you must have the
oss:ListObjectspermission. For more information, see Attach a custom policy to a RAM user.
Sample code
The following sample code provides an example of how to call the ListObjectsV2 operation to list objects in a 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();
Common scenarios
Is this page helpful?