我正在使用 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(...);
最佳答案
这是因为 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();
})
您可以在此处的文档中阅读有关子目录的更多信息:https://cloud.google.com/storage/docs/gsutil/addlhelp/HowSubdirectoriesWork
关于node.js - 谷歌云存储 + Nodejs : How to delete a folder and all its content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959059/