Todos os produtos
Search
Central de documentação

Object Storage Service:Listar objetos

Última atualização: Sep 22, 2026

Este tópico descreve como listar todos os objetos, um número específico de objetos e objetos cujos nomes contêm um prefixo definido em um bucket do Object Storage Service (OSS).

Métodos

Você pode chamar os métodos list ou listV2 para listar até 1.000 objetos em um bucket por operação. Ajuste os parâmetros conforme a necessidade para obter os resultados desejados. Por exemplo, é possível indicar um ponto de partida, filtrar objetos e subdiretórios de um caminho específico ou habilitar paginação. A tabela a seguir detalha as diferenças entre as duas abordagens:

  • Ao utilizar o método list, a resposta inclui por padrão os dados dos proprietários dos objetos.

  • Ao utilizar o método listV2, defina o parâmetro fetch-owner para informar se deseja incluir ou omitir os dados dos proprietários na resposta.

    Nota

    Recomendamos o uso do método listV2 para listar objetos em buckets com controle de versão.

As tabelas a seguir apresentam os parâmetros disponíveis ao chamar os métodos list e listV2.

  • Chame o método list para listar objetos

    A tabela abaixo detalha os parâmetros aceitos pelo método list.

    Parameter

    Type

    Description

    prefix

    string

    O prefixo que deve estar presente nos nomes dos objetos listados.

    delimiter

    string

    Caractere usado para agrupar objetos por nome.

    marker

    string

    Nome do objeto que indica o início da listagem. Se informado, a operação retorna os objetos que aparecem após esse valor na ordem alfabética.

    max-keys

    number

    string

    Quantidade máxima de objetos retornados.

    encoding-type

    'url'

    ''

    Indica que os nomes dos objetos na resposta serão codificados em URL.

  • Chame o método listV2 para listar objetos

    A tabela abaixo detalha os parâmetros aceitos pelo método listV2.

    Parameter

    Type

    Description

    prefix

    string

    O prefixo que deve estar presente nos nomes dos objetos listados.

    continuation-token

    string

    Token que indica a posição a partir da qual a próxima página será obtida.

    delimiter

    string

    Caractere usado para agrupar objetos por nome.

    max-keys

    number

    string

    Quantidade máxima de objetos retornados.

    start-after

    string

    Nome do objeto que indica o início da listagem. Se informado, a operação retorna os objetos que aparecem após esse valor na ordem alfabética.

    fetch-owner

    boolean

    Define se as informações sobre os proprietários dos objetos serão incluídas na resposta.

    encoding-type

    'url'

    ''

    Indica que os nomes dos objetos na resposta serão codificados em URL.

Listar objetos com listagem simples

O exemplo de código a seguir mostra como listar objetos em um bucket específico. Por padrão, a operação retorna até 100 objetos.

  • Chame o método list para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
        // By default, if no parameter is specified, up to 100 objects can be returned. 
        const result = await client.list();
        console.log(result);
    }
    
    list();
  • Chame o método listV2 para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
        // By default, if no parameter is specified, up to 100 objects can be returned. 
        const result = await client.listV2();
        console.log(result);
    }
    
    list();

Listar uma quantidade específica de objetos em um bucket

O exemplo a seguir demonstra como limitar a quantidade de objetos retornados em um bucket ajustando o parâmetro max-keys.

  • Chame o método list para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
        const result = await client.list({
            // Specify that the first 10 objects in alphabetical order are returned. 
          "max-keys": 10
      });
        console.log(result);
    }
    
    list();
  • Chame o método listV2 para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
        const result = await client.listV2({
            // Specify that the first 10 objects in alphabetical order are returned. 
          "max-keys": 10
      });
        console.log(result);
    }
    
    list();

Listar objetos com um prefixo definido

O exemplo a seguir mostra como listar objetos cujos nomes começam com um determinado prefixo usando o parâmetro prefix.

  • Chame o método list para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
      const result = await client.list({
        // List 10 objects. 
        "max-keys": 10,
        // List objects whose names contain the foo/ prefix. 
        prefix: 'foo/'
      });
      console.log(result);
    }
    
    list();
  • Chame o método listV2 para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
      const result = await client.listV2({
        // List 10 objects. 
        "max-keys": 10,
        // List objects whose names contain the foo/ prefix. 
        prefix: 'foo/'
      });
      console.log(result);
    }
    
    list();

Listar objetos que aparecem após um nome específico na ordem alfabética

O exemplo a seguir ilustra como listar objetos que vêm depois de uma string definida pelos parâmetros marker ou start-after.

  • Chame o método list para listar objetos

    O parâmetro marker determina a partir de qual nome a listagem será iniciada.

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    // List the objects whose names are alphabetically after the object name test. By default, up to 100 objects are listed. 
    const marker = 'test'
    async function list () {
      const result = await client.list({
        marker
      });
      console.log(result);
    }
    
    list();
  • Chame o método listV2 para listar objetos

    O parâmetro start-after determina a partir de qual nome a listagem será iniciada.

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
      const result = await client.listV2({
        // List the objects and subfolders whose names are alphabetically after a/b in the a/ folder. 
        delimiter: '/',
        prefix: 'a/',
        'start-after': 'a/b'
      });
      console.log(result.objects, result.prefixes);
    }
    
    list();

Listar todos os objetos de um bucket por página

O código abaixo demonstra como paginar a listagem de todos os objetos de um bucket. Use o parâmetro max-keys para definir quantos itens cada página pode conter.

  • Chame o método list para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    let marker = null; 
    
    // List up to 20 objects on each page. 
    const maxKeys = 20;
    
    async function list () {
      do {
        const result = await client.list({
          marker: marker, 
          'max-keys': maxKeys
        });
        marker = result.nextMarker;
        console.log(result);
      } while (marker);
    }
    
    list();
  • Chame o método listV2 para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    async function list () {
      let continuationToken = null;
      // List up to 20 objects on each page. 
      const maxKeys = 20;
      do {
        const result = await client.listV2({
          'continuation-token': continuationToken,
          'max-keys': maxKeys
          });
        continuationToken = result.nextContinuationToken;
            console.log(result);
      }while(continuationToken)
    }
    
    list();

Listar objetos e informações do proprietário

O exemplo a seguir mostra como listar os objetos junto com os dados dos proprietários:

const OSS = require('ali-oss');

const client = new OSS({
  // 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: 'yourregion',
  // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name. 
  bucket: 'yourbucketname'
});

// By default, the information about the object owners is not listed. To include the object owner information in the response, you must set the fetch-owner parameter to true. 
async function list () {
  const result = await client.listV2({
    'fetch-owner': true
  });
  console.log(result.objects);
}

list();

Listar objetos e subpastas em um diretório específico

O Object Storage Service (OSS) armazena os objetos em uma estrutura plana. Um diretório é, na verdade, um objeto de zero bytes com nome terminado em barra (/). É possível fazer upload e download desse objeto. Por padrão, o console do OSS exibe como diretório qualquer objeto com nome finalizado em /. Para acessar o código completo de criação de diretórios, visite GitHub.

  • Se você definir o prefix como o nome de um diretório na solicitação, a operação listará os objetos e subdiretórios que contêm esse prefixo.

  • Caso informe um prefixo e defina delimiter como barra (/), a resposta trará os objetos e subdiretórios daquele caminho que iniciam com o prefixo indicado. Cada subdiretório aparece como um único elemento em CommonPrefixes, sem expor os itens internos a essas pastas.

Considere que o bucket contenha os objetos a seguir:

foo/x
foo/y
foo/bar/a
foo/bar/b
foo/hello/C/1
foo/hello/C/2
...
foo/hello/C/9999

O exemplo a seguir demonstra como chamar os métodos list ou listV2 para listar objetos e subpastas de um diretório específico.

  • Chame o método list para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    // Call the listDir function and configure different prefixes to list the required objects. 
    async function listDir(dir) {
      try {
        const result = await client.list({
          prefix: dir,
          delimiter: '/'
        });
        if (result && result.prefixes) {
          result.prefixes.forEach(subDir => {
            console.log('SubDir: %s', subDir);
          });
        }
        if (result && result.objects) {
          result.objects.forEach(obj => {
            console.log('Object: %s', obj.name);
          });
        }
      } catch (e) {
        console.log(e);
      }
    }
    
    listDir('foo/');
    // Expected result:
    // SubDir: foo/bar/
    // SubDir: foo/hello/
    // Object: foo/x
    // Object: foo/y
    
    listDir('foo/bar/');
    // Expected result:
    // Object: foo/bar/a
    // Object: foo/bar/b
    
    listDir('foo/hello/C/');
    // Expected result:
    // Object: foo/hello/C/1
    // Object: foo/hello/C/2
    // ...
    // Object: foo/hello/C/9999
  • Chame o método listV2 para listar objetos

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // 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: 'yourregion',
      // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the bucket name. 
      bucket: 'yourbucketname'
    });
    
    // Call the listV2Dir function and configure different prefixes to list the required objects. 
    async function listV2Dir(dir) {
      try {
        const result = await client.listV2({
          prefix: dir,
          delimiter: '/'
        });
        if (result && result.prefixes) {
          result.prefixes.forEach(subDir => {
            console.log('SubDir: %s', subDir);
          });
        }
        if (result && result.objects) {
          result.objects.forEach(obj => {
            console.log('Object: %s', obj.name);
          });
        }
      } catch (e) {
        console.log(e);
      }
    }
    
    listDir('foo/');
    // Expected result:
    // SubDir: foo/bar/
    // SubDir: foo/hello/
    // Object: foo/x
    // Object: foo/y
    
    listDir('foo/bar/');
    // Expected result:
    // Object: foo/bar/a
    // Object: foo/bar/b
    
    listDir('foo/hello/C/');
    // Expected result:
    // Object: foo/hello/C/1
    // Object: foo/hello/C/2
    // ...
    // Object: foo/hello/C/9999

Referências