Use the listObjectsV2 method to list objects in a bucket and retrieve their metadata. This page covers five scenarios: basic listing, prefix filtering, delimiter-based virtual directory listing, paginated listing, and retrieving owner information.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket
The
oss:ListObjectspermission. For details, see Attach a custom policy to a RAM userThe region where the bucket is located. For supported regions and endpoints, see Regions and endpoints
Basic listing
The following example initializes a client with Security Token Service (STS) temporary credentials and lists all objects in a bucket.
import Client, { RequestError } from '@aliyun/oss';
const client = new Client({
accessKeyId: 'yourAccessKeyId', // AccessKey ID from STS
accessKeySecret: 'yourAccessKeySecret', // AccessKey secret from STS
securityToken: 'yourSecurityToken', // Security token from STS
region: 'oss-cn-hangzhou', // Region where the bucket is located
});
const listObjectsV2 = async () => {
try {
const res = await client.listObjectsV2({
bucket: 'yourBucketName',
});
console.log(JSON.stringify(res));
} catch (err) {
if (err instanceof RequestError) {
console.log('code: ', err.code);
console.log('message: ', err.message);
console.log('requestId: ', err.requestId);
console.log('status: ', err.status);
console.log('ec: ', err.ec);
} else {
console.log('unknown error: ', err);
}
}
};
listObjectsV2();Common scenarios
All examples below use the same listObjectsV2 method with RAM user credentials. Replace the placeholder values with your own credentials and bucket name before running any example.
Parameters
The following table lists all parameters supported by listObjectsV2.
| Parameter | Type | Description |
|---|---|---|
bucket | string | Name of the bucket. |
prefix | string | Filters results to objects whose keys start with this value. |
delimiter | string | Groups keys that share a common prefix up to the delimiter into commonPrefixes. Use / to simulate folder navigation. |
continuationToken | string | Token returned by the previous response to fetch the next page. Initially undefined. |
fetchOwner | boolean | Set to true to include owner information in the response. Defaults to false. |
Error handling
All examples use the RequestError class to distinguish known API errors from unexpected errors. When a RequestError is caught, log the following fields to diagnose the issue.
| Field | Description |
|---|---|
err.code | The error code |
err.message | The error message |
err.requestId | The request ID, useful for support tickets |
err.status | The HTTP status code |
err.ec | The extended error code |