11

I If you are using NodeJS GCS client library and want to list directories in your bucket, how do you do that?

srfrnk
  • 2,459
  • 1
  • 17
  • 32

1 Answers1

9

First add the dependency for the NodeJS GCS client library into your package.json file by running:

npm -i @google-cloud/storage --save

Then add this into your code to list all files:

const storage = require('@google-cloud/storage');
...
const projectId = '<<<<<your-project-id-here>>>>>';
const gcs = storage({
    projectId: projectId
});

let bucketName = '<<<<<your-bucket-name-here>>>>>';
let bucket = gcs.bucket(bucketName);
bucket.getFiles({}, (err, files,apires) => {console.log(err,files,apires)});

This will return all files with full path into files.

To list only directories you must workaround a quirk in the client library that requires you to use no auto pagination and then returns an extra argument to the CB. To do so change the code to this:

let cb=(err, files,next,apires) => {
    console.log(err,files,apires);
    if(!!next)
    {
        bucket.getFiles(next,cb);
    }
}
bucket.getFiles({delimiter:'/', autoPaginate:false}, cb);

This will return a list of directories under the root path with trailing / in apires.prefixes.

To list only directories under foo/ directory use this code:

let cb=(err, files,next,apires) => {
    console.log(err,files,apires);
    if(!!next)
    {
        bucket.getFiles(next,cb);
    }
}
bucket.getFiles({prefix:'foo/', delimiter:'/', autoPaginate:false}, cb);
srfrnk
  • 2,459
  • 1
  • 17
  • 32
  • The syntax has changed. You should now use `const {Storage} = require('@google-cloud/storage');` and `const gcs = new Storage({ projectId: projectId });`. Here is an example from the docs: https://googleapis.dev/nodejs/storage/latest/Bucket.html#getFiles – twiz Jul 10 '19 at 02:42
  • A question: shouldn't the options '{prefix:'foo/', delimiter:'/', autoPaginate:false}' also be used on the inner getFiles ? – Jørgen Rasmussen Jul 24 '20 at 15:06