1
I如果您正在使用NodeJS GCS客户端库并想列出存储桶中的目录,那么您如何做到这一点?如何使用NodeJS列出GCS存储桶中的目录
I如果您正在使用NodeJS GCS客户端库并想列出存储桶中的目录,那么您如何做到这一点?如何使用NodeJS列出GCS存储桶中的目录
首先,添加的NodeJS GCS客户端库的依赖到你的package.json
文件通过运行:
然后添加到您的代码此列出所有文件:
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
。
要仅列出目录,您必须在客户端库中解决一个问题,该问题需要您不使用自动分页,然后向CB返回一个额外的参数。要做到这一点的代码改成这样:
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
尾随/
。
要只列出目录下foo/
目录,使用此代码:
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);