node.js - 谷歌云存储 + Nodejs : How to delete a folder and all its content

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

我正在使用 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/

相关文章:

javascript - node-gyp - 找不到库头文件

javascript - DriveApp.getStorageUsed() 与 DriveApp.getFiles() 返回的文件大小总和不匹配。

google-cloud-storage - 批量文件上传到云存储

firebase - us-central1 的函数调用配额限制...已弃用?

javascript - 如何使用服务器上的 Node 从客户端 JavaScript 上传到 Google Cloud Storage?

python - 使用 Django 将文件发送到 GCS 的最佳方式

javascript - Heroku:找出哪个文件夹是活的

javascript - KeyboardAvoidingView "Padding"无法正常工作

javascript - res.should.have.status 给我错误

javascript - 有没有办法通过 JavaScript 使用 Google AutoML?