4

I would like to display all the folders from my Google Cloud Storage bucket on my Node.js app but there is only getFiles() function.

For example a folder named /abc, with 2 files in it /a & /b. I would like to only get /abc/ and no /abc/a & /abc/b.

app.js

router.get('/', async(req, res) => {
  let bucketName = 'my-bucket'

  const storage = Storage();

  const [files] = await storage.bucket(bucketName).getFiles();
  let app = [];
  for (const file of files) {
    const [metadata] = await file.getMetadata();
    app.push(metadata);
  };
  res.render('views/list.ejs', {
    apps : app, 
  });
  });
Nibrass H
  • 2,403
  • 1
  • 8
  • 14
Gwen7
  • 45
  • 1
  • 5

2 Answers2

4

It's worth noting that like S3 on AWS. GCS does not have 'directories' but paths.

https://cloud.google.com/storage/docs/gsutil/addlhelp/HowSubdirectoriesWork

You can access the file names from .name on the objects returned from GCS. And you can add a prefix to the .getFiles() call.

router.get('/', async (req, res) => {
    const bucketName = 'my-bucket'

    const storage = Storage()

    const [files] = await storage.bucket(bucketName).getFiles({ prefix: '/abc'})
    const objectNames = files.map(file => file.name)

    res.render('views/list.ejs', {
        apps: objectNames,
    })
})

razki
  • 1,171
  • 2
  • 8
  • 16
  • Yes, but it display the directory name + file name "abc/a" – Gwen7 Apr 14 '20 at 15:27
  • Updated the answer. – razki Apr 14 '20 at 15:31
  • Ok thanks! if i have a lot of different paths, what prefix should i put ? – Gwen7 Apr 14 '20 at 15:55
  • Well you've asked to get the contents of things prefixed with `/abc` but you don't want to return `/abc/a` - This is not possible as the object "a" is prefixed with `/abc/`. Take a look at the documentation I've put in the answer. – razki Apr 14 '20 at 17:10
  • If you want to emit a particular file or 'folder pass a `.getFiles({ delimiter: '/c' })` – razki Apr 14 '20 at 17:15
  • if you wanted to further filter those files you would need to process these yourself – razki Apr 14 '20 at 17:20
0

"folders" (prefixes) are being returned as part of the getFiles result:

example based on Get Only The Top Level Objects of A Bucket

const options = {
    prefix: "folder/",
    autoPaginate: false,
    delimiter: "/"
};

const [files, nextQuery, apiResponse] = await storage.bucket(bucketName).getFiles(options);
// folders should be in apiResponse.prefixes
console.log(apiResponse.prefixes)
Adi
  • 1,263
  • 1
  • 13
  • 24