UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【GCS】Bucket内のファイルをディレクトリ階層で絞り込む

node.jsからBucket内のファイルリストを取得する際、なにもオプションで指定しないと、そのBucket内の全てのファイルが取得されてしまう

Bucket内のあるディレクトリ配下のみを取得したかったので、その方法を調査した

prefixオプションを使う

ドキュメントからprefixオプションが相当しそう

Name Type Attributes Default Description
prefix string optional Filter results to objects whose names begin with this prefix.

googleapis.dev

次のような階層をもつBucketであれば

my-bucket
├ sub-dir1
└ sub-dir2

以下のように絞り込んで取得できる

const bucket = storage.bucket("my-bucket"); 
const files = await bucket.getFiles({ prefix: 'sub-dir1/' }).catch(err => {
    throw err;
  });