I'm using Node 10 and the gcs API.
Trying to delete a folder and all its content, but I can't figure how.
Nothing found about deleting folders in the API documentation.
I tried the following code, that works with single files, but no with an entire folder:
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(...);
That is because Google Cloud Storage does not really have folders (or as they are called "subdirectories"), just files that begin with a prefix.
For example, your folder album-1
looks like a folder in the Google Cloud Storage web UI, but in reality, it is just a way to represent files that their name begins with album1/...
, aka album1/pic1.jpg
and so on.
In order to delete the "folder" album1
, you actually need to delete all the files that begin with album1/...
. You could do that using the following steps:
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();
})
You can read more about subdirectories at the docs here: https://cloud.google.com/storage/docs/gsutil/addlhelp/HowSubdirectoriesWork
Solution apported by @Ohad Chaet, with some adjustments:
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();
});
You can do this
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 })))
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.