Updated on 2024-11-26 GMT+08:00

Listing Objects in a Bucket (SDK for Node.js)

If you have any questions during development, post them on the Issues page of GitHub.

Function

This API lists some or all of the objects in a bucket. You can configure the prefix, number, or start position as the filter to list objects. Returned objects are listed in alphabetical order by object name.

Restrictions

Method

ObsClient.listObjects(params)

Request Parameters

Table 1 ListObjectsInput

Parameter

Type

Mandatory (Yes/No)

Description

Bucket

string

Yes

Explanation:

Bucket name

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain a period (.) and a hyphen (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets with the same name in the same region, no error will be reported, and the bucket attributes comply with those set in the first creation request.

Value range:

The value can contain 3 to 63 characters.

Default value:

None

Marker

string

No

Explanation:

Object name to start with when listing objects in a bucket. Objects after the specified object are returned in alphabetical order.

Restrictions:

This parameter is only used for listing objects with a single version.

Value range:

The value can contain 1 to 1,024 characters.

Default value:

None

Prefix

string

No

Explanation:

Name prefix that the objects to be listed must contain

Assume that you have the following objects: logs/day1, logs/day2, logs/day3, and ExampleObject.jpg. If you specify logs/ as the prefix, logs/day1, logs/day2, and logs/day3 will be returned. If this parameter is left blank and there are no other filtering criteria, all objects in the bucket will be returned.

Restrictions:

None

Value range:

The value can contain 1 to 1,024 characters.

Default value:

None

MaxKeys

number

No

Explanation:

The maximum number of objects returned in the response in alphabetical order

Restrictions:

None

Value range:

The value ranges from 1 to 1000. If the specified value is greater than 1000, only 1,000 objects are returned.

Default value:

1000

Delimiter

string

No

Explanation:

Object names are grouped by this parameter, which is often used with Prefix. If a prefix is specified, objects with the same string from the prefix to the first delimiter are grouped into one CommonPrefixes. If no prefix is specified, objects with the same string from the first character to the first delimiter are grouped into one CommonPrefixes.

Assume that a bucket has objects abcd, abcde, and bbcde in it. If Delimiter is set to d and Prefix is set to a, objects abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix. If only Delimiter is set to d, objects abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix, and bbcde is placed separately into another CommonPrefixes with bbcd as the prefix.

For a parallel file system, if this parameter is not specified, all the content in the directory is recursively listed by default, and subdirectories are also listed. In big data scenarios, parallel file systems usually have multiple directory levels, and each directory level has a large number of objects. In such case, you are advised to configure [delimiter=/] to list only the content in the current directory, without the content in subdirectories, to make the listing more efficient.

Restrictions:

None

Value range:

The value can contain 1 to 1,024 characters.

Default value:

None

EncodingType

string

No

Explanation:

Encoding type for some elements in the response. If Delimiter, Marker, Prefix, CommonPrefixes, NextMarker, and Key contain control characters (special characters) that are not supported by the XML 1.0 standard, set this parameter to url.

Restrictions:

None

Value range:

url

Default value:

None. If you leave this parameter blank, encoding is not applied.

Responses

Table 2 Responses

Type

Description

Table 3

NOTE:

This API returns a Promise response, which requires the Promise or async/await syntax.

Explanation:

Returned results. For details, see Table 3.

Table 3 Response

Parameter

Type

Description

CommonMsg

ICommonMsg

Explanation:

Common information generated after an API call is complete, including the HTTP status code and error code. For details, see Table 4.

InterfaceResult

Table 5

Explanation:

Results outputted for a successful call. For details, see Table 5.

Restrictions:

This parameter is not included if the value of Status is greater than 300.

Table 4 ICommonMsg

Parameter

Type

Description

Status

number

Explanation:

HTTP status code returned by the OBS server.

Value range:

A status code is a group of digits indicating the status of a response. It ranges from 2xx (indicating successes) to 4xx or 5xx (indicating errors). For details, see Status Codes.

Code

string

Explanation:

Error code returned by the OBS server.

Message

string

Explanation:

Error description returned by the OBS server.

HostId

string

Explanation:

Request server ID returned by the OBS server.

RequestId

string

Explanation:

Request ID returned by the OBS server.

Id2

string

Explanation:

Request ID2 returned by the OBS server.

Indicator

string

Explanation:

Error code details returned by the OBS server.

Table 5 ListObjectsOutput

Parameter

Type

Description

RequestId

string

Explanation:

Request ID returned by the OBS server

Location

string

Explanation:

Region where a bucket is located.

Bucket

string

Explanation:

Bucket name

Prefix

string

Explanation:

Object name prefix, which is consistent with that set in the request.

Assume that you have the following objects: logs/day1, logs/day2, logs/day3, and ExampleObject.jpg. If you specify logs/ as the prefix, logs/day1, logs/day2, and logs/day3 will be returned. If this parameter is left blank and there are no other filtering criteria, all objects in the bucket will be returned.

Marker

string

Explanation:

Object name to start with when listing objects. Objects after the specified object are returned in alphabetical order.

Delimiter

string

Explanation:

Object names are grouped by this parameter, which is often used with Prefix. If a prefix is specified, objects with the same string from the prefix to the first delimiter are grouped into one CommonPrefixes. If no prefix is specified, objects with the same string from the first character to the first delimiter are grouped into one CommonPrefixes.

Assume that a bucket has objects abcd, abcde, and bbcde in it. If Delimiter is set to d and Prefix is set to a, objects abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix. If only Delimiter is set to d, objects abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix, and bbcde is placed separately into another CommonPrefixes with bbcd as the prefix.

For a parallel file system, if this parameter is not specified, all the content in the directory is recursively listed by default, and subdirectories are also listed. In big data scenarios, parallel file systems usually have multiple directory levels, and each directory level has a large number of objects. In such case, you are advised to configure [delimiter=/] to list only the content in the current directory, without the content in subdirectories, to make the listing more efficient.

MaxKeys

number

Explanation:

The maximum number of objects returned in the response in alphabetical order. This parameter corresponds to the same parameter in the request.

IsTruncated

string

Explanation:

Whether all results are returned in the response. A maximum of 1,000 objects can be listed at a time. If the number of objects is greater than 1,000, the objects beyond 1,000 cannot be returned.

Value range:

  • true: Not all results are returned.
  • false: All results are returned.

NextMarker

string

Explanation:

Where in the bucket the next listing begins. If not all results are returned, the response contains this parameter to mark the last object listed in the request. In a subsequent request, you can set Marker to the value of this parameter to list the remaining objects.

Contents

Content[]

Explanation:

List of objects in the bucket. For details, see Content.

CommonPrefixes

CommonPrefix[]

Explanation:

List of object name prefixes grouped based on the Delimiter parameter (if specified)

Value range:

See Table 7.

EncodingType

string

Explanation:

Encoding type for some elements in the response. If Delimiter, Marker, Prefix, CommonPrefixes, NextMarker, and Key contain control characters (special characters) that are not supported by the XML 1.0 standard, set this parameter to url.

Table 6 Content

Parameter

Type

Description

Key

string

Explanation:

Object name. An object is uniquely identified by an object name in a bucket. An object name is a complete path of the object that does not contain the bucket name.

For example, if the address for accessing the object is examplebucket.obs.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt.

LastModified

string

Explanation:

Time when the object was last modified, in UTC.

ETag

string

Explanation:

Base64-encoded, 128-bit MD5 value of an object. ETag is the unique identifier of the object contents and is used to determine whether the contents of an object are changed. For example, if the ETag value is A when an object is uploaded and B when the object is downloaded, this indicates the contents of the object have been changed. The ETag reflects changes to an object's contents, not its metadata. Objects created by the upload and copy operations are assigned unique ETags after being encrypted using MD5.

Restrictions:

If an object is encrypted using server-side encryption, the ETag is not the MD5 value of the object.

Size

number

Explanation:

Object size, in bytes.

Owner

Owner

Explanation:

Object owner. The value contains the domain ID and name of the object owner. For details, see Table 8.

StorageClass

string

Explanation:

Object storage class.

Type

string

Explanation:

Type of the object

Value range:

  • NORMAL indicates a regular object.
  • APPENDABLE indicates an appendable object.
Table 7 CommonPrefix

Parameter

Type

Description

Prefix

string

Explanation:

Prefix of objects in a bucket

Value range:

The value can contain 1 to 1,024 characters.

Default value:

None

Table 8 Owner

Parameter

Type

Mandatory (Yes/No)

Description

ID

string

Yes if used as a request parameter

Explanation:

Account (domain) ID of the owner

Value range:

To obtain the account ID, see How Do I Get My Account ID and User ID? (SDK for Node.js).

Default value:

None

DisplayName

string

No

Explanation:

Account name of the owner

Default value:

None

Code Examples: Simple Listing

The following sample code shows how to list objects in simple mode. A maximum of 1,000 objects can be returned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here in this example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

async function listObjects() {
  try {
    const params = {
      // Specify the bucket name.
      Bucket: "examplebucket",
    };
    // List objects in a bucket.
    const result = await obsClient.listObjects(params);
    if (result.CommonMsg.Status <= 300) {
      console.log("List objects under the bucket(%s) successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      for (let j = 0; j < result.InterfaceResult.Contents.length; j++) {
        const val = result.InterfaceResult.Contents[j];
        console.log('Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d',
          j, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size);
      };
      return;
    };
    console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
    console.log("Status: %d", result.CommonMsg.Status);
    console.log("Code: %s", result.CommonMsg.Code);
    console.log("Message: %s", result.CommonMsg.Message);
    console.log("RequestId: %s", result.CommonMsg.RequestId);
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};

listObjects();
  • A maximum of 1,000 objects can be listed each time. If a bucket contains more than 1,000 objects, InterfaceResult.IsTruncated in the response is true, indicating not all objects were listed. In such case, you can use InterfaceResult.NextMarker to obtain the start position for next listing.
  • If you want to obtain all objects in a specified bucket, use pagination. For details, see Code Examples: Listing All Objects Using Pagination.

Code Examples: Listing a Specified Number of Objects

Sample code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
    access_key_id: process.env.ACCESS_KEY_ID,
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here in this example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

async function listObjects() {
  try {
    const params = {
      // Specify the bucket name.
      Bucket: "examplebucket",
      // Specify the maximum number of objects to be returned in alphabetic order. The default value is 1000. 100 is used in this example.
      MaxKeys: 100,
    };
    // List objects in a bucket.
    const result = await obsClient.listObjects(params);
    if (result.CommonMsg.Status <= 300) {
      console.log("List objects under the bucket(%s) successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      for (let j = 0; j < result.InterfaceResult.Contents.length; j++) {
        const val = result.InterfaceResult.Contents[j];
        console.log('Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d',
          j, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size);
      };
      return;
    };
    console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
    console.log("Status: %d", result.CommonMsg.Status);
    console.log("Code: %s", result.CommonMsg.Code);
    console.log("Message: %s", result.CommonMsg.Message);
    console.log("RequestId: %s", result.CommonMsg.RequestId);
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};

listObjects();

Code Examples: Listing Objects by Prefix

Sample code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');
// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here in this example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

async function listObjects() {
  try {
    const params = {
      // Specify the bucket name.
      Bucket: "examplebucket",
      // Specify an object prefix (test/ in this example). Objects whose names contain the specified prefix will be listed.
      Prefix: "test/",
      // Specify the maximum number of objects to be returned in alphabetic order. The default value is 1000. 100 is used in this example.
      MaxKeys: 100,
    };
    
    // List objects in a bucket.
    const result = await obsClient.listObjects(params);
    if (result.CommonMsg.Status <= 300) {
      console.log("List objects under the bucket(%s) successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      for (let j = 0; j < result.InterfaceResult.Contents.length; j++) {
        const val = result.InterfaceResult.Contents[j];
        console.log('Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d',
          j, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size);
      };
      return;
    };
    console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
    console.log("Status: %d", result.CommonMsg.Status);
    console.log("Code: %s", result.CommonMsg.Code);
    console.log("Message: %s", result.CommonMsg.Message);
    console.log("RequestId: %s", result.CommonMsg.RequestId);
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};

listObjects();

Code Examples: Specifying a Start Position for Listing

Sample code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here in this example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

async function listObjects() {
  try {
    const params = {
      // Specify the bucket name.
      Bucket: "examplebucket",
      // Specify an object prefix (test/ in this example). Objects whose names contain the specified prefix will be listed.
      Prefix: "test/",
      // Specify the maximum number of objects to be returned in alphabetic order. The default value is 1000. 100 is used in this example.
      MaxKeys: 100,
      // Specify the position (test/test2 in this example) where the object listing starts.
      Marker: "test/test2",
    };
    // List objects in a bucket.
    const result = await obsClient.listObjects(params);
    if (result.CommonMsg.Status <= 300) {
      console.log("List objects under the bucket(%s) successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      for (let j = 0; j < result.InterfaceResult.Contents.length; j++) {
        const val = result.InterfaceResult.Contents[j];
        console.log('Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d',
          j, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size);
      };
      return;
    };
    console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
    console.log("Status: %d", result.CommonMsg.Status);
    console.log("Code: %s", result.CommonMsg.Code);
    console.log("Message: %s", result.CommonMsg.Message);
    console.log("RequestId: %s", result.CommonMsg.RequestId);
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};

listObjects();

Code Examples: Listing All Objects Using Pagination

Sample code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here in this example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

async function listObjects() {
  try {
    const params = {
      // Specify the bucket name.
      Bucket: "examplebucket",
      // Specify an encoding type. url is used in this example. If the objects to list contain special characters, this parameter must be passed.
      EncodingType: "url",
    };
    while (true) {
      // List object versions in the bucket.
      const result = await obsClient.listObjects(params);
      if (result.CommonMsg.Status > 300) {
        console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
        console.log("Status: %d", result.CommonMsg.Status);
        console.log("Code: %s", result.CommonMsg.Code);
        console.log("Message: %s", result.CommonMsg.Message);
        console.log("RequestId: %s", result.CommonMsg.RequestId);
        return;
      };
      console.log("List objects under the bucket(%s) successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      for (let j = 0; j < result.InterfaceResult.Contents.length; j++) {
        const val = result.InterfaceResult.Contents[j];
        console.log('Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d',
          j, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size);
      };
      if (result.InterfaceResult.IsTruncated === "true") {
        params.KeyMarker = result.InterfaceResult.NextKeyMarker;
      } else {
        break;
      };
    };
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};

listObjects();

Code Examples: Listing All Objects in a Folder

OBS does not involve folders like in a file system. All elements in buckets are objects. Folders are actually objects whose sizes are 0 and whose names end with a slash (/). When you set a folder name as the prefix, objects in this folder will be listed. Sample code is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here in this example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

async function listObjects() {
  try {
    const params = {
      // Specify the bucket name.
      Bucket: "examplebucket",
      // Specify an object prefix (test/ in this example). Objects whose names contain the specified prefix will be listed.
      Prefix: "test/",
      // Specify an encoding type. url is used in this example. If the objects to list contain special characters, this parameter must be passed.
      EncodingType: "url",
    };
    let count = 1
    while (true) {
      // List object versions in the bucket.
      const result = await obsClient.listObjects(params);
      if (result.CommonMsg.Status > 300) {
        console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
        console.log("Status: %d", result.CommonMsg.Status);
        console.log("Code: %s", result.CommonMsg.Code);
        console.log("Message: %s", result.CommonMsg.Message);
        console.log("RequestId: %s", result.CommonMsg.RequestId);
        return;
      };
      console.log("List objects under the bucket(%s) successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      for (let j = 0; j < result.InterfaceResult.Contents.length; j++) {
        const val = result.InterfaceResult.Contents[j];
        console.log('Content[%d]-OwnerId:%s, ETag:%s, Key:%s, LastModified:%s, Size:%d',
          count++, val.Owner.ID, val.ETag, val.Key, val.LastModified, val.Size);
      };
      if (result.InterfaceResult.IsTruncated === "true") {
        params.Marker = result.InterfaceResult.NextMarker;
      } else {
        break;
      };
    };
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};

listObjects();