
# 列举桶列表(Node.js SDK)
![](https://support.huaweicloud.com/sdk-nodejs-devg-obs/public_sys-resources/notice_3.0-zh-cn.png)
开发过程中，您有任何问题可以在GitHub上[提交issue](https://github.com/huaweicloud/huaweicloud-sdk-nodejs-obs/issues)，或者在[华为云对象存储服务论坛](https://bbs.huaweicloud.com/forum/forum-620-1.html)中发帖求助。
#### 功能介绍
OBS桶是对象的容器，您上传的文件都存放在桶中。调用获取桶列表接口，可列举当前账号所有区域下符合指定条件的桶。返回结果以桶名的字典序排序。
#### 接口约束
- 您必须拥有obs:bucket:ListAllMyBuckets权限，才能获取桶列表。建议使用IAM进行授权，配置方式详见[使用IAM自定义策略](https://support.huaweicloud.com/usermanual-obs/obs_03_0121.html)。

- OBS支持的Region与Endpoint的对应关系，详细信息请参见[地区与终端节点](https://console.huaweicloud.com/apiexplorer/#/endpoint/OBS)。
 
#### 方法定义
```
ObsClient.listBuckets(params)
```
#### 请求参数说明
表1请求参数列表 
| **参数名称**      | **参数类型** | **是否必选** | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                               |
|:---|:---|:---|:---|
| QueryLocation | boolean  | 可选       | **参数解释：** 是否同时查询桶的区域位置。 **约束限制：** 无 **取值范围：** - true：同时查询桶的区域位置  - false：不查询桶的区域位置   **默认取值：** false |
| BucketType    | string   | 可选       | **参数解释：** 列举指定类型的桶。 **约束限制：** 无 **取值范围：** 桶类型取值可参见[BucketType]。 **默认取值：** 无，如果不赋值则默认获取所有桶和并行文件系统列表。                                                                            |
   
 表2BucketType 
| **可选值** | **说明**              |
|:---|:---|
| OBJECT  | 对应类型为对象存储桶。         |
| POSIX   | 对应类型为并行文件系统（POSIX）。 |
   
#### 返回结果说明
表3返回结果 
| **参数类型**                                                                                                                                                | 描述                                                                                      |
|:---|:---|
| [表4] 说明： 该接口返回是一个Promise类型，需要使用Promise、async/await语法处理。 | **参数解释：** 接口返回信息，详见[表4]。 |
   
 表4Response 
| **参数名称**        | **参数类型**                                              | 描述                                                                                                                                                                                                         |
|:---|:---|:---|
| CommonMsg       | [ICommonMsg]        | **参数解释：** 接口调用完成后的公共信息，包含HTTP状态码，操作失败的错误码等，详见[ICommonMsg]。                                                                                |
| InterfaceResult | [ListBucketsOutput] | **参数解释：** 操作成功后的结果数据，详见[ListBucketsOutput]。 **约束限制** **：** 当Status大于300时为空。 |
   
 表5ICommonMsg 
| **参数名称**  | **参数类型** |                                                                                                                                                                                                       **描述**                                                                                                                                                                                                        |
|---|---|---|
| Status    | number   | **参数解释：** OBS服务端返回的HTTP状态码。 **取值范围：** 状态码是一组从2xx（成功）到4xx或5xx（错误）的数字代码，状态码表示了请求响应的状态。完整的状态码列表请参见[状态码](https://support.huaweicloud.com/api-obs/obs_04_0114.html)。 |
| Code      | string   | **参数解释：** OBS服务端返回的错误码。                                                                                                                                                                                                                                                                                                                                    |
| Message   | string   | **参数解释：** OBS服务端返回的错误描述。                                                                                                                                                                                                                                                                                                                                  |
| HostId    | string   | **参数解释：** OBS服务端返回的请求服务端ID。                                                                                                                                                                                                                                                                                                                               |
| RequestId | string   | **参数解释：** OBS服务端返回的请求ID。                                                                                                                                                                                                                                                                                                                                  |
| Id2       | string   | **参数解释：** OBS服务端返回的请求ID2。                                                                                                                                                                                                                                                                                                                               |
| Indicator | string   | **参数解释：** OBS服务端返回的详细错误码。                                                                                                                                                                                                                                                                                                                                |
   
 表6ListBucketsOutput 
| **参数名称**  | **参数类型**                                        | **描述**                                                                                                                                                                   |
|:---|:---|:---|
| RequestId | string                                          | **参数解释：** OBS服务端返回的请求ID。 **默认取值：** 无                                           |
| Owner     | [Owner]         | **参数解释：** 桶的所有者。 **取值范围：** 桶所有者取值参见[Owner]。        |
| Buckets   | [Bucket]\[\] | **参数解释：** 桶信息列表。 **取值范围：** 桶信息取值参见[Bucket]。 |
   
 表7Owner 
| **参数名称**    | **参数类型** | **是否必选**  | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|:---|:---|:---|:---|
| ID          | string   | 作为请求参数时必选 | **参数解释：** 所有者的账号ID，即domain_id。 **取值范围：** 如何获取账号ID请参见[如何获取账号ID和用户ID？(Node.js SDK)](https://support.huaweicloud.com/sdk-nodejs-devg-obs/obs_29_1715.html) **默认取值：** 无 |
| DisplayName | string   | 可选        | **参数解释：** 所有者的账号用户名。 **默认取值：** 无                                                                                                                                                                                                                                                          |
   
 表8Bucket 
| **参数名称**     | **参数类型** | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
|:---|:---|:---|
| BucketName   | string   | **参数解释** **：** 桶名。 **约束限制：** - 桶的名字需全局唯一，不能与已有的任何桶名称重复，包括其他用户创建的桶。  - 桶命名规则如下： - 3～63个字符，数字或字母开头，支持小写字母、数字、"-"、"."。  - 禁止使用类IP地址。  - 禁止以"-"或"."开头及结尾。  - 禁止两个"."相邻（如："my..bucket"）。  - 禁止"."和"-"相邻（如："my-.bucket"和"my.-bucket"）。     **默认取值：** 无 |
| CreationDate | string   | **参数解释** **：** 桶的创建时间。 **默认取值：** 无                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Location     | string   | **参数解释** **：** 桶所在的区域。 **约束限制：** 该参数定义了桶将会被创建在哪个区域，如果使用的终端节点是obs.myhuaweicloud.com，可以不携带此参数；如果使用的终端节点不是obs.myhuaweicloud.com，则必须携带此参数。 **取值范围：** 当前有效的OBS区域和终端节点的更多信息，请参考[地区和终端节点](https://developer.huaweicloud.com/endpoint?OBS)。终端节点即调用API的请求地址，不同服务不同区域的终端节点不同，您可以向企业管理员获取区域和终端节点信息。 **默认取值：** 终端节点为obs.myhuaweicloud.com且用户未设定区域时，默认为华北-北京一（cn-north-1）。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| BucketType   | string   | **参数解释** **：** 桶类型。 **取值范围：** - 对象桶：OBJECT  - 并行文件系统：POSIX。   **默认取值：** 无                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
   
#### 代码示例
可以通过ObsClient.listBuckets列举桶。以下代码展示如何列举所有桶列表。
```
// 引入obs库
// 使用npm安装
const ObsClient = require("esdk-obs-nodejs");
// 使用源码安装
// var ObsClient = require('./lib/obs');
// 创建ObsClient实例
const obsClient = new ObsClient({
  // 推荐通过环境变量获取AKSK，这里也可以使用其他外部引入方式传入，如果使用硬编码可能会存在泄露风险
  // 您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // 【可选】如果使用临时AK/SK和SecurityToken访问OBS，同样建议您尽量避免使用硬编码，以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK，也可以使用其他外部引入方式传入
  // security_token: process.env.SECURITY_TOKEN,
  // endpoint填写Bucket对应的Endpoint, 这里以华北-北京四为例，其他地区请按实际情况填写
  server: "https://obs.cn-north-4.myhuaweicloud.com",
});
async function listBuckets() {
  try {
    const params = {
      // 指定桶列表中是否存在Location字段，此处以true为例，默认是false
      QueryLocation: true,
      // 指定桶类型，此处以为对象桶为例，即获取对象桶列表，默认不设置则获取所有对象桶和并行文件系统列表
      BucketType: "OBJECT",
    };
    // 列举桶列表
    const result = await obsClient.listBuckets(params);
    if (result.CommonMsg.Status <= 300) {
      console.log("List buckets successful!", params.Bucket);
      console.log("RequestId: %s", result.CommonMsg.RequestId);
      console.log('Owner:');
      console.log('ID: %s', result.InterfaceResult.Owner.ID);
      console.log('Name: %s', result.InterfaceResult.Owner.Name);
      console.log('Buckets:');
      for (let i = 0; i < result.InterfaceResult.Buckets.length; i++) {
          const val = result.InterfaceResult.Buckets[i];
          console.log("Bucket[%d]-Name:%s,CreationDate:%s,Location: %s",
            i, val.BucketName, val.CreationDate, val.Location);
      };
      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);
  };
};
listBuckets();
```
