Google Cloud Storage + Nodejs:如何删除文件夹及其所有内容

Mig*_*ara 2 node.js google-cloud-storage google-cloud-platform

我正在使用 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(...);
Run Code Online (Sandbox Code Playgroud)

Oha*_*aet 5

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

例如,您的文件夹album-1看起来像 Google Cloud Storage Web UI 中的文件夹,但实际上,它只是一种表示名称以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();
})
Run Code Online (Sandbox Code Playgroud)

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