【问题标题】:Google Cloud Storage + Nodejs: How to delete a folder and all its contentGoogle Cloud Storage + Nodejs:如何删除文件夹及其所有内容
【发布时间】:2019-12-11 23:54:15
【问题描述】:

我正在使用 Node 10 和 gcs API。

试图删除一个文件夹及其所有内容,但我不知道怎么做。

在 API 文档中没有找到关于删除文件夹的内容。

我尝试了以下代码,它适用于单个文件,但不适用于整个文件夹:

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({
    projectId: 'my-id'
});
const bucket = storage.bucket('photos');

// Attempt to delete a folder and its files:
bucket
    .file('album-1')
    .delete()
    .then(...)
    .catch(...);

【问题讨论】:

标签: node.js google-cloud-platform google-cloud-storage


【解决方案1】:

这是因为 Google Cloud Storage 并没有真正的文件夹(或称为“子目录”),只有以前缀开头的文件。

例如,您的文件夹 album-1 在 Google Cloud Storage 网络用户界面中看起来像一个文件夹,但实际上,它只是一种表示文件名以 album1/... 开头的文件的方式,也就是 album1/pic1.jpg 等等开。

为了删除“文件夹”album1,您实际上需要删除所有以album1/... 开头的文件。您可以使用以下步骤来做到这一点:

let dirName = 'album-1';
// List all the files under the bucket
let files = await bucket.getFiles();
// Filter only files that belong to "folder" album-1, aka their file.id (name) begins with "album-1/"
let dirFiles = files.filter(f => f.id.includes(dirName + "/"))
// Delete the files
dirFiles.forEach(async file => {
    await file.delete();
})

您可以在此处的文档中阅读有关子目录的更多信息:https://cloud.google.com/storage/docs/gsutil/addlhelp/HowSubdirectoriesWork

【讨论】:

  • 谢谢!您的解决方案有效,但做了一些小改动。我将在其他帖子中写出确切的解决方案。还有一个问题:如果我的存储桶中有数百张图像,迭代所有文件是个好主意,还是“files.filter”有更好的选择?
  • 您应该在 getFiles 中使用前缀选项,而不是绝对获取每个文件
【解决方案2】:

@Ohad Chaet 提出的解决方案,并进行了一些调整:

let dirName = 'album-1';

let files = await bucket.getFiles();

let dirFiles = files[0].filter(f => f.id.includes(dirName + '/'));

dirFiles.forEach(async file => {
    await file.delete();
});

【讨论】:

  • 小心includes,因为它还会删除包含文件夹名称的文件。如果你使用它,我建议你使用f.id.includes(dirName + "/")
  • 出于某种原因,我需要“%2F”而不是“/”
猜你喜欢
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
相关资源
最近更新 更多