En este tema se describe cómo enumerar todos los objetos, un número específico de objetos y aquellos cuyos nombres contienen un prefijo determinado dentro de un bucket de Object Storage Service (OSS).
Métodos
Puede llamar al método list o listV2 para enumerar hasta 1,000 objetos a la vez en un bucket. Configure los parámetros adecuados para listar los objetos de distintas maneras. Por ejemplo, puede especificar una posición inicial, enumerar objetos y subdirectorios dentro de un directorio concreto o paginar los resultados. A continuación se describen las diferencias entre los métodos list y listV2:
Cuando llama al método
listpara enumerar objetos, la información sobre los propietarios se devuelve de forma predeterminada.-
Si utiliza el método
listV2, debe configurar el parámetro fetch-owner para indicar si desea incluir los datos de los propietarios en la respuesta.NotaSe recomienda llamar al método
listV2para enumerar objetos en un bucket con control de versiones habilitado.
Las siguientes tablas describen los parámetros que puede configurar al llamar a los métodos list y listV2 para enumerar objetos.
-
Llamar al método list para enumerar objetos
La siguiente tabla detalla los parámetros disponibles cuando se invoca el método list.
Parámetro
Tipo
Descripción
prefix
string
Prefijo obligatorio en los nombres de los objetos enumerados.
delimiter
string
Carácter utilizado para agrupar los objetos por nombre.
marker
string
Nombre del objeto a partir del cual comienza la operación de listado. Si se especifica este parámetro, se devuelven los objetos cuyos nombres son alfabéticamente posteriores al valor de marker.
max-keys
number
string
Número máximo de objetos devueltos.
encoding-type
'url'
''
Indica que los nombres de los objetos en la respuesta se codifican mediante URL.
-
Llamar al método listV2 para enumerar objetos
A continuación se muestran los parámetros configurables al utilizar el método listV2.
Parámetro
Tipo
Descripción
prefix
string
Prefijo obligatorio en los nombres de los objetos enumerados.
continuation-token
string
Token que indica la posición desde donde se obtiene la lista de objetos.
delimiter
string
Carácter utilizado para agrupar los objetos por nombre.
max-keys
number
string
Número máximo de objetos devueltos.
start-after
string
Nombre del objeto a partir del cual comienza la operación de listado. Si se especifica este parámetro, se devuelven los objetos cuyos nombres son alfabéticamente posteriores al valor de start-after.
fetch-owner
boolean
Determina si se incluye la información de los propietarios en la respuesta.
encoding-type
'url'
''
Indica que los nombres de los objetos en la respuesta se codifican mediante URL.
Enumerar objetos con un listado simple
El siguiente código de ejemplo muestra cómo enumerar los objetos de un bucket específico. De forma predeterminada, se listan hasta 100 objetos.
-
Llamar al método list para enumerar 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(); -
Llamar al método listV2 para enumerar 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();
Enumerar un número específico de objetos en un bucket
Este fragmento de código ilustra cómo limitar la cantidad de objetos enumerados en un bucket mediante el parámetro max-keys.
-
Llamar al método list para enumerar 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(); -
Llamar al método listV2 para enumerar 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();
Enumerar objetos cuyos nombres contienen un prefijo específico
El siguiente ejemplo demuestra cómo filtrar los objetos de un bucket por prefijo utilizando el parámetro prefix.
-
Llamar al método list para enumerar 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(); -
Llamar al método listV2 para enumerar 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();
Enumerar objetos cuyos nombres son alfabéticamente posteriores a uno específico
El siguiente código de ejemplo muestra cómo listar los objetos cuyos nombres aparecen después de la cadena indicada en los parámetros marker o startAfter, según el orden alfabético.
-
Llamar al método list para enumerar objetos
El parámetro marker define el nombre del objeto a partir del cual comienza la operación de listado.
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(); -
Llamar al método listV2 para enumerar objetos
El parámetro startAfter define el nombre del objeto a partir del cual comienza la operación de listado.
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();
Enumerar todos los objetos de un bucket por página
El siguiente ejemplo ilustra cómo paginar el listado completo de objetos en un bucket. Configure el parámetro max-keys para establecer el número máximo de objetos mostrados en cada página.
-
Llamar al método list para enumerar 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(); -
Llamar al método listV2 para enumerar 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();
Enumerar objetos e información de sus propietarios
El siguiente código de ejemplo muestra cómo obtener tanto la lista de objetos como los datos de sus propietarios:
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();
Enumerar objetos y subcarpetas dentro de una carpeta específica
OSS emplea una estructura plana para almacenar los objetos. Un directorio es simplemente un objeto de cero bytes cuyo nombre termina con una barra diagonal (/), el cual se puede cargar y descargar. De forma predeterminada, cualquier objeto cuyo nombre termine con una barra diagonal (/) se muestra como un directorio en la consola de OSS. Para consultar el código de ejemplo completo sobre cómo crear directorios, visite GitHub.
Si establece el parámetro prefix con el nombre de un directorio en la solicitud, se enumeran los objetos y subdirectorios cuyos nombres contienen dicho prefijo.
Si especifica un prefijo y configura delimiter con una barra diagonal (/) en la solicitud, se listan los objetos y subdirectorios del directorio que comienzan con ese prefijo. Cada subdirectorio aparece como un único elemento de resultado en CommonPrefixes. Los objetos y directorios contenidos en esos subdirectorios no se incluyen en el listado.
Suponga que un bucket contiene los siguientes objetos:
foo/x
foo/y
foo/bar/a
foo/bar/b
foo/hello/C/1
foo/hello/C/2
...
foo/hello/C/9999
El siguiente código de ejemplo muestra cómo llamar al método list o listV2 para enumerar los objetos y subcarpetas de una carpeta determinada.
-
Llamar al método list para enumerar 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 -
Llamar al método listV2 para enumerar 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
Referencias
Para consultar el código de ejemplo completo sobre cómo enumerar objetos, visite GitHub.
Para obtener más información sobre las operaciones de API que permiten enumerar objetos, consulte ListObjects (GetBucket) y ListObjectsV2 (GetBucketV2).