List files in a paginated manner

List objects in a bucket with no autopagination, showing how to move to the next set of objects.

Code sample

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFilesPaginated() {
  const bucket = storage.bucket(bucketName);
  const [files, queryForPage2] = await bucket.getFiles({autoPaginate: false});

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });

  // Page through the next set of results using "queryForPage2"
  if (queryForPage2 !== null) {
    const [files, queryForPage3] = await bucket.getFiles(queryForPage2);

    console.log('Files:');
    files.forEach(file => {
      console.log(file.name);
    });

    // If necessary, continue cursoring using "queryForPage3"
  }
}

listFilesPaginated().catch(console.error);

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.