Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list directories in a GCS bucket using NodeJS

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

like image 236
srfrnk Avatar asked May 07 '17 08:05

srfrnk


1 Answers

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);
like image 159
srfrnk Avatar answered Oct 13 '22 22:10

srfrnk