[英]Google Cloud Storage: How to Delete a folder (recursively) in Python
[英]Google Cloud Storage + Nodejs: How to delete a folder and all its content
我正在使用节点 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 云存储网络用户界面中的文件夹,但实际上,它只是一种表示名称以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
@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();
});
你可以这样做
async deleteFolder(bucketName: string, folder: string): Promise<void> {
const storage = new Storage({
projectId: your project Id
});
const bucket = storage.bucket(bucketName);
const [files] = await bucket.getFiles({ prefix: `${folder}/` });
await Promise.allSettled(files.map(file => file.delete({ ignoreNotFound: true })))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.