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

后端 未结 7 956
误落风尘
误落风尘 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:13

    According to accepted answer I created promise returned function, so you can chain it.

    function emptyBucket(bucketName){
        let currentData;
        let params = {
            Bucket: bucketName,
            Prefix: 'folder/'
        };
    
        return S3.listObjects(params).promise().then(data => {
            if (data.Contents.length === 0) {
                throw new Error('List of objects empty.');
            }
    
            currentData = data;
    
            params = {Bucket: bucketName};
            params.Delete = {Objects:[]};
    
            currentData.Contents.forEach(content => {
                params.Delete.Objects.push({Key: content.Key});
            });
    
            return S3.deleteObjects(params).promise();
        }).then(() => {
            if (currentData.Contents.length === 1000) {
                emptyBucket(bucketName, callback);
            } else {
                return true;
            }
        });
    }
    

提交回复
热议问题