如何使用 NodeJS 列出 GCS 存储桶中的目录 [英] How to list directories in a GCS bucket using NodeJS
问题描述
如果您使用 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)});
这将返回所有文件以及文件
的完整路径.
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屋!