-1

When running (new Storage()).bucket('my-bucket-name').getFiles(), I get a list of objects with this structure. All the items are set to public and I'd rather not process the objects to piece together the public urls by "hand" (https://storage.cloud.google.com/[object.metadata.bucket]/[object.metadata.name]) and I was wondering if the NodeJs client for GCP offers anything like this.

I found a similar link here except for python.

Thank you!

Wytrzymały Wiktor
  • 11,492
  • 5
  • 29
  • 37
reactor
  • 1,722
  • 1
  • 14
  • 34

1 Answers1

4

As mentioned in the thread you posted, there is no direct way to do this through the client libraries that Google has in place. There are some objects that allow you to get the URL directly, but not all of them do.

Due to this, It's safer for you to piece the URLs inside your code. As you mention, and as referred in the Google Docs through this document, you can use the URL pattern http(s)://storage.googleapis.com/[bucket]/[object] in order to quickly construct the URL.

Given the response of the API, you can create it through a small cycle such as

function main(bucketName = 'my-bucket') {
  // The ID of your GCS bucket
  const bucketName = 'your-unique-bucket-name';
  // The string for the URL
  const url = 'https://storage.googleapis.com/';

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

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

  async function listFiles() {
    // Lists files in the bucket
    const [files] = await storage.bucket(bucketName).getFiles();

    console.log('URLs:');
    files.forEach(file => {
      console.log(url.concat(bucketName,'/',file.name));
    });
  }

  listFiles().catch(console.error);
}

This was adapted from the sample code for listing files over at GCPs GitHub

rsalinas
  • 1,507
  • 8
  • 9