如何使用NodeJS列出GCS存储桶中的目录 [英] How to list directories in a GCS bucket using NodeJS

查看:123
本文介绍了如何使用NodeJS列出GCS存储桶中的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I如果您使用的是NodeJS GCS客户端库,并且想在存储桶中列出目录,您该怎么做?

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

推荐答案

首先通过运行以下命令将NodeJS GCS客户端库的依赖项添加到您的package.json文件中:

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)});

这将返回具有完整路径的所有文件files.

This will return all files with full path into files.

要仅列出目录,您必须解决客户端库中的一个怪癖,即要求您不使用自动分页,然后向CB返回一个额外的参数.为此,将代码更改为此:

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);

这将返回根路径下的目录列表,在apires.prefixes中以/结尾.

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

要仅列出foo/目录下的目录,请使用此代码:

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);

这篇关于如何使用NodeJS列出GCS存储桶中的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆