Este tópico descreve como listar todos os objetos, um número específico de objetos e objetos cujos nomes contêm um prefixo específico em um bucket do Object Storage Service (OSS).
Métodos
Use o método list ou listV2 para listar até 1.000 objetos por vez em um bucket. Configure parâmetros para listar objetos de diferentes maneiras. Por exemplo, liste objetos a partir de uma posição inicial específica, liste objetos e subdiretórios em um diretório específico ou liste objetos por página. A seção a seguir descreve as diferenças entre os métodos list e listV2:
Ao usar o método
listpara listar objetos, o sistema retorna as informações sobre os proprietários dos objetos por padrão.-
Ao usar o método
listV2para listar objetos, configure o parâmetro fetch-owner para especificar se a resposta deve incluir as informações sobre os proprietários dos objetos.NotaRecomendamos usar o método
listV2para listar objetos em um bucket com versionamento.
As tabelas a seguir descrevem os parâmetros configuráveis ao usar os métodos list e listV2 para listar objetos.
-
Chamar o método list para listar objetos
A tabela a seguir descreve os parâmetros configuráveis ao usar o método list para listar objetos.
Parâmetro
Tipo
Descrição
prefix
string
Prefixo obrigatório nos nomes dos objetos listados.
delimiter
string
Caractere usado para agrupar objetos por nome.
marker
string
Nome do objeto a partir do qual a operação de listagem começa. Se este parâmetro for especificado, o sistema retornará os objetos cujos nomes estejam alfabeticamente após o valor do parâmetro marker.
max-keys
number
string
Número máximo de objetos retornados.
encoding-type
'url'
''
Especifica que os nomes dos objetos na resposta têm codificação URL.
-
Chamar o método listV2 para listar objetos
A tabela a seguir detalha os parâmetros disponíveis ao usar o método listV2 para listar objetos.
Parâmetro
Tipo
Descrição
prefix
string
Prefixo obrigatório nos nomes dos objetos listados.
continuation-token
string
Token que especifica a posição a partir da qual a lista de objetos é obtida.
delimiter
string
Caractere usado para agrupar objetos por nome.
max-keys
number
string
Número máximo de objetos retornados.
start-after
string
Nome do objeto a partir do qual a operação de listagem começa. Se este parâmetro for especificado, o sistema retornará os objetos cujos nomes estejam alfabeticamente após o valor do parâmetro start-after.
fetch-owner
boolean
Especifica se a resposta deve incluir as informações sobre os proprietários dos objetos.
encoding-type
'url'
''
Especifica que os nomes dos objetos na resposta têm codificação URL.
Listar objetos usando listagem simples
O código de exemplo a seguir mostra como listar objetos em um bucket especificado. Por padrão, o sistema lista até 100 objetos.
-
Chamar 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(); -
Chamar 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 um número especificado de objetos em um bucket
O exemplo de código a seguir demonstra como listar uma quantidade definida de objetos em um bucket ao configurar o parâmetro max-keys.
-
Chamar 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(); -
Chamar 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 cujos nomes contêm um prefixo especificado
O código de exemplo abaixo ilustra como listar objetos cujos nomes contêm um prefixo definido em um bucket, utilizando o parâmetro prefix.
-
Chamar 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(); -
Chamar 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 cujos nomes estão alfabeticamente após um nome de objeto especificado
O exemplo de código a seguir apresenta como listar objetos cujos nomes estão alfabeticamente após uma string especificada pelo parâmetro marker ou startAfter.
-
Chamar o método list para listar objetos
O parâmetro marker especifica o nome do objeto a partir do qual a operação de listagem começa.
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(); -
Chamar o método listV2 para listar objetos
O parâmetro startAfter especifica o nome do objeto a partir do qual a operação de listagem começa.
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 em um bucket por página
O código de exemplo a seguir mostra como listar todos os objetos em um bucket especificado, paginação por paginação. Configure o parâmetro max-keys para definir o número máximo de objetos listados em cada página.
-
Chamar 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(); -
Chamar 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 de código a seguir demonstra como listar objetos e as informações de seus 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 uma pasta especificada
O OSS utiliza uma estrutura plana para armazenar objetos. Um diretório é um objeto de zero bytes cujo nome termina com uma barra (/). É possível fazer upload e download desse objeto. Por padrão, o console do OSS exibe um objeto cujo nome termina com uma barra (/) como um diretório. Para obter o código de exemplo completo usado para criar diretórios, visite o GitHub.
Se você definir prefix como um nome de diretório na solicitação, o sistema listará os objetos e subdiretórios cujos nomes contêm o prefixo.
Caso especifique um prefixo e defina delimiter como uma barra (/) na solicitação, o sistema listará os objetos e subdiretórios cujos nomes começam com o prefixo especificado no diretório. Cada subdiretório aparece como um único elemento de resultado em CommonPrefixes. Os objetos e diretórios dentro desses subdiretórios não são listados.
Suponha que os seguintes objetos estejam armazenados em um bucket:
foo/x
foo/y
foo/bar/a
foo/bar/b
foo/hello/C/1
foo/hello/C/2
...
foo/hello/C/9999
O código de exemplo a seguir mostra como usar o método list ou listV2 para listar objetos e subpastas em uma pasta especificada.
-
Chamar 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 -
Chamar 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
Para acessar o código de exemplo completo usado para listar objetos, visite o GitHub.
Para mais informações sobre as operações de API usadas para listar objetos, consulte ListObjects (GetBucket) e ListObjectsV2 (GetBucketV2).