Todos os produtos
Search
Central de documentação

Object Storage Service:Listar buckets (Harmony SDK)

Última atualização: Jul 03, 2026

Um bucket é um contêiner que armazena objetos. Todos os objetos ficam armazenados em um bucket. É possível listar buckets que atendem a condições específicas em todas as regiões da sua conta Alibaba Cloud. A lista de buckets é organizada em ordem alfabética.

Precauções

  • Para obter mais informações sobre as regiões compatíveis com o OSS e seus endpoints, consulte Regiões e Endpoints.

  • Para listar buckets, é necessária a permissão oss:ListBuckets. Para mais detalhes, consulte Conceder políticas de acesso personalizadas para usuários RAM.

  • O código a seguir lista buckets em todas as regiões da sua conta Alibaba Cloud. Esta operação não permite listar buckets de uma região específica. O resultado não depende da região do endpoint especificado.

Código de exemplo

O código abaixo demonstra como listar todos os buckets em todas as regiões da sua conta Alibaba Cloud.

import Client, { RequestError } from '@aliyun/oss';

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the Security Token Service (STS) temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the Security Token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
});

// List all buckets.
const listBuckets = async () => {
  try {
    // Call the listBuckets method to list all buckets.
    const res = await client.listBuckets({});

    // Print the result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch and handle request errors.
    if (err instanceof RequestError) {
      console.log('Error code: ', err.code); // Error code
      console.log('Error message: ', err.message); // Error description
      console.log('Request ID: ', err.requestId); // Unique identifier of the request
      console.log('HTTP status code: ', err.status); // HTTP response status code
      console.log('Error category: ', err.ec); // Error category
    } else {
      console.log('Unknown error: ', err); // Error that is not of the RequestError type
    }
  }
};

// Call the function to list all buckets.
listBuckets();

Outros cenários

Listar buckets com um prefixo especificado

O exemplo a seguir mostra como listar buckets com o prefixo bucketNamePrefix em todas as regiões da sua conta Alibaba Cloud.

import Client, { RequestError } from '@aliyun/oss';

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the Security Token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
});

// List buckets that start with a specific prefix.
const listBucketsWithPrefix = async () => {
  try {
    // Call the listBuckets method and specify the prefix parameter to filter bucket names.
    const res = await client.listBuckets({
      prefix: 'bucketNamePrefix' // Specify the prefix for bucket names.
    });

    // Print the result.
    console.log(JSON.stringify(res));
  } catch (err) {
    if (err instanceof RequestError) {
      console.log('Error code: ', err.code);
      console.log('Error message: ', err.message);
      console.log('Request ID: ', err.requestId);
      console.log('HTTP status code: ', err.status);
      console.log('Error category: ', err.ec);
    } else {
      console.log('Unknown error: ', err);
    }
  }
};

// Call the function to list buckets that start with a specific prefix.
listBucketsWithPrefix();

Listar todos os buckets usando um token de paginação (marker)

Este trecho ilustra como listar todos os buckets utilizando um token de paginação (marker).

import Client, { RequestError } from '@aliyun/oss';

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the Security Token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
});

// List all buckets using a pagination token (marker).
const listBucketsWithMarker = async () => {
  try {
    let marker: string | undefined; // The pagination token. It is initially empty.
    let isTruncated = true; // Indicates whether there is more data to retrieve.

    // Loop to retrieve all buckets until there is no more data.
    while (isTruncated) {
      const res = await client.listBuckets({
        marker // The current pagination token.
      });

      // Print the result.
      console.log(JSON.stringify(res));

      // Update the pagination status.
      isTruncated = res.data.isTruncated; // Indicates whether there is more data.
      marker = res.data.nextMarker; // The next pagination token.
    }
  } catch (err) {
    if (err instanceof RequestError) {
      console.log('Error code: ', err.code);
      console.log('Error message: ', err.message);
      console.log('Request ID: ', err.requestId);
      console.log('HTTP status code: ', err.status);
      console.log('Error category: ', err.ec);
    } else {
      console.log('Unknown error: ', err);
    }
  }
};

// Call the function to list all buckets using a pagination token.
listBucketsWithMarker();

Referências