Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of folders from Google Cloud Platform bucket using Node.js

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, 
  });
  });
like image 564
Gwen7 Avatar asked Oct 13 '26 13:10

Gwen7


1 Answers

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,
    })
})

like image 157
razki Avatar answered Oct 15 '26 04:10

razki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!