How can I delete folder on s3 with node.js?

后端 未结 7 934
误落风尘
误落风尘 2021-01-30 10:48

Yes, I know. There is no folder concept on s3 storage. but I really want to delete a specific folder from s3 with node.js. I tried two solutions, but both didn\'t work. My code

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 11:19

    Here is an implementation in ES7 with an async function and using listObjectsV2 (the revised List Objects API):

    async function emptyS3Directory(bucket, dir) {
        const listParams = {
            Bucket: bucket,
            Prefix: dir
        };
    
        const listedObjects = await s3.listObjectsV2(listParams).promise();
    
        if (listedObjects.Contents.length === 0) return;
    
        const deleteParams = {
            Bucket: bucket,
            Delete: { Objects: [] }
        };
    
        listedObjects.Contents.forEach(({ Key }) => {
            deleteParams.Delete.Objects.push({ Key });
        });
    
        await s3.deleteObjects(deleteParams).promise();
    
        if (listedObjects.IsTruncated) await emptyS3Directory(bucket, dir);
    }
    

    To call it:

    await emptyS3Directory(process.env.S3_BUCKET, 'images/')
    

提交回复
热议问题