Todos los productos
Search
Centro de documentos

Object Storage Service:List files (Node.js SDK)

Última actualización: Sep 03, 2026

Este tema describe cómo listar todos los objetos, un número específico de objetos o aquellos con un prefijo determinado dentro de un bucket cuando el control de versiones está habilitado.

Listar información de todos los objetos en un bucket

A continuación se muestra el código para listar la información de versión de todos los objetos, incluidos los marcadores de eliminación, en un bucket específico:

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

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure 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 version information of all objects, including delete markers.
async function getObjectVersions() {
  let nextKeyMarker = null;
  let nextVersionMarker = null;
  let versionListing = null;
  do {
    versionListing = await client.getBucketVersions({
      keyMarker: nextKeyMarker,
      versionIdMarker: nextVersionMarker,
    });

    versionListing.objects.forEach((o) => {
      console.log(`${o.name}, ${o.versionId}`);
    });
    versionListing.deleteMarker.forEach((o) => {
      console.log(`${o.name}, ${o.versionId}`);
    });

    nextKeyMarker = versionListing.NextKeyMarker;
    nextVersionMarker = versionListing.NextVersionIdMarker;
  } while (versionListing.isTruncated);
}

getObjectVersions();

Listar información de versión de objetos con un prefijo específico

El siguiente código muestra cómo listar la información de versión de los objetos que tienen un prefijo determinado:

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

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure 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 version information of objects that have the "test-" prefix.
async function getObjectVersionsByPrefix() {
  let nextKeyMarker = null;
  let nextVersionMarker = null;
  let versionListing = null;
  const prefix = 'test-'
  do {
    versionListing = await client.getBucketVersions({
      keyMarker: nextKeyMarker,
      versionIdMarker: nextVersionMarker,
      prefix
    })
    versionListing.objects.forEach(o => {
      console.log(`${o.name}, ${o.versionId}`)
    })
    versionListing.deleteMarker.forEach(o => {
      console.log(`${o.name}, ${o.versionId}`)
    })
    nextKeyMarker = versionListing.NextKeyMarker;
    nextVersionMarker = versionListing.NextVersionIdMarker;
  } while (versionListing.isTruncated);
}

getObjectVersionsByPrefix();

Listar información de versión de un número específico de objetos

El siguiente fragmento de código ilustra cómo obtener la información de versión de una cantidad limitada de objetos:

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

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure 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 getObjectVersionByNumber() {
  // List the version information of a maximum of 100 objects.
  const versionListing = await client.getBucketVersions({
    "max-keys": 100,
  });
  // Obtain the version information of the objects. If versioning is disabled, the VersionId is "none".
  versionListing.objects.forEach((o) => {
    console.log(`${o.name}, ${o.versionId}`);
  });
  versionListing.deleteMarker.forEach((o) => {
    console.log(`${o.name}, ${o.versionId}`);
  });
}

getObjectVersionByNumber();

Función de carpetas

OSS no cuenta con un concepto nativo de carpeta; en su lugar, todos los elementos se almacenan como objetos. Es posible simular una carpeta si crea un objeto de 0 KB cuyo nombre termine con una barra diagonal (/). Este objeto se puede cargar y descargar. La consola de OSS muestra como carpetas aquellos objetos cuyos nombres terminan con una barra diagonal (/).

Para simular la funcionalidad de carpetas, utilice los parámetros delimiter y prefix:

  • Si establece el parámetro prefix con el nombre de una carpeta, OSS lista todos los objetos cuyo nombre comienza con dicho prefijo. Esto devuelve todos los objetos contenidos en la carpeta y sus subdirectorios.

  • Si configura el parámetro prefix y define el parámetro delimiter como una barra diagonal (/), OSS enumera únicamente los objetos y subdirectorios del nivel superior de esa carpeta. Los subdirectorios se devuelven en el elemento CommonPrefixes, sin listar los objetos que se encuentran dentro de ellos.

Suponga que un bucket contiene cuatro objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi y fun/movie/007.avi4. Se utiliza la barra diagonal (/) como separador de carpetas. Los siguientes ejemplos muestran cómo listar objetos mediante la simulación de carpetas.

Listar información de versión de objetos en el directorio raíz

El siguiente código muestra cómo listar la información de versión de los objetos ubicados en el directorio raíz:

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

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure 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'
});

// Set the delimiter parameter to a forward slash (/) to list the version information of objects and the names of folders in the root directory.
async function getRootObjectVersions() {
  let nextKeyMarker = null;
  let nextVersionMarker = null;
  let versionListing = null;
  do {
    versionListing = await client.getBucketVersions({
      keyMarker: nextKeyMarker,
      versionIdMarker: nextVersionMarker,
      delimiter: "/",
    });
    nextKeyMarker = versionListing.NextKeyMarker;
    nextVersionMarker = versionListing.NextVersionIdMarker;
    console.log(versionListing);
  } while (versionListing.isTruncated);
}

getRootObjectVersions();

Listar archivos y subdirectorios en un directorio

El siguiente código muestra cómo listar los objetos y subdirectorios contenidos en un directorio específico:

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

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure 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'
});

// Set the prefix parameter to get all files and folders in the foo/ directory. Also, set the delimiter parameter to a forward slash (/) to act as the folder separator.
async function getObjectVersionsByPrefixAndDirectory() {
  let nextKeyMarker = null;
  let nextVersionMarker = null;
  let versionListing = null;
  let prefix = "foo/";
  do {
    versionListing = await client.getBucketVersions({
      keyMarker: nextKeyMarker,
      versionIdMarker: nextVersionMarker,
      prefix,
      delimiter: "/",
    });
    nextKeyMarker = versionListing.NextKeyMarker;
    nextVersionMarker = versionListing.NextVersionIdMarker;
    console.log(versionListing);
  } while (versionListing.isTruncated);
}

getObjectVersionsByPrefixAndDirectory();

Referencias

Para obtener más información sobre la operación de API para listar objetos, consulte ListObjectVersions (GetBucketVersions).