How to list only files not folder in GCS?

Viewed 1482

I'm new to GCS. I'm trying to list the files in a "folder" & download them, however my list is return the folder name as index 0.

How do I only list the files name and not the name of the directory? Or should I just shift() the array after I get the list back?

const prefix = 'testFiles/'; //contains jpgs
const delimiter = '/';
    const options = {
        prefix: prefix,
      };

      if (delimiter) {
        options.delimiter = delimiter;
      }

const [files] = await storage.bucket(bucketName).getFiles();

files.forEach((file, i) => {
    options.destination = `./downloads/${i}.jpg`
    console.log(options);
    file.download(options)
});
}
1 Answers

Google Cloud Storage does not have real "folders". Instead, they are emulated using the prefix and delimiter parameters to the List Objects method.

The way you're doing it is correct. But when you list with a prefix, all objects that start with that prefix are returned, up to the delmiter, if specified. That means, like you found, that if have a "directory placeholder" object (an object that ends in /), it will be returned. Note that it also means any "subdirectories" of that prefix will also be returned. For example, if you have the following list of objects in a bucket:

testFiles/
testFiles/a
testFiles/b
testFiles/c/d
testFiles/v

If you call list objects with prefix=testFiles/ and delimiter=/, you'll have the following returned:

items =
  testFiles/
  testFiles/a
  testFiles/b
  testFiles/v
prefixes =
  testFiles/c/

This is because testFiles/ is actually an object in your bucket in GCS.

Related