简体   繁体   中英

List Folders in Google Cloud Storage Bucket using Node.js

I've been looking for a way to retrieve only directories inside a bucket but not what's in them.

As per Google Cloud Storage Docs one can filter by prefix by:

const Storage = require('@google-cloud/storage');  

const storage = new Storage();

const options = {
  prefix: prefix,
  delimiter: '/'
};

storage
  .bucket(bucketName)
  .getFiles(options)
  .then(results => {
    const files = results[0];

    console.log('Files:');
    files.forEach(file => {
      console.log(file.name);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

I've tried with several combinations using prefix: "" , or prefix: "*" or prefix: "\\" and so on but I can't get to make it return only the folders.

Has anybody been able to do it?

As a matter of fact, getFiles method is not reading folders in the way you are using it. I have adapted the code in this post to print my buckets:

const storage = require('@google-cloud/storage');

const projectId = 'PROJECT_ID';
const gcs = storage({
    projectId: projectId
});

let bucketName = 'BUCKET_NAME';
let bucket = gcs.bucket(bucketName);
// bucket.getFiles({}, (err, files,apires) => {console.log(err,files,apires)});


let cb=(err, files,next,apires) => {
    /*console.log('Err:');
    console.log('Files:');
    console.log(files);*/
    console.log('Apires:');
    console.log(typeof apires);
    console.log(apires);
    console.log(apires.prefixes);
    if(!!next)
    {   
        bucket.getFiles(next,cb);
    }   
}

bucket.getFiles({delimiter:'/', autoPaginate:false}, cb);

/* 
// List folders inside folders
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);
*/ 

And, even if this is not useful in this case, I suggest you to use regular expression to determine specific formats for names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM