I If you are using NodeJS GCS client library and want to list directories in your bucket, how do you do that?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With