How to list directories in a GCS bucket using NodeJS

后端 未结 1 1211
离开以前
离开以前 2021-01-12 11:40

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

相关标签:
1条回答
  • 2021-01-12 12:28

    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);
    
    0 讨论(0)
提交回复
热议问题