Vu Thai Duy
Vu Thai Duy

Reputation: 179

Nodejs delete folder on Amazon S3 with aws-sdk

I'm facing issue of deleting folder which contains photos inside on Amazon S3

1. Create folder

var params = {Bucket: S3_BUCKET, Key: "test/", ACL:"public-read"};  
s3.putObject(params, function(err, data) {  

}); 

2. Upload photo

var body = fs.createReadStream(filePath);  
var params = {Bucket: S3_BUCKET, Key: "test/flower.jpgg", Body: body, ContentType:"image/jpeg", ACL:"public-read"};  

s3.upload(params, function(err, data) {

});

3. Delete folder

var params = {Bucket: S3_BUCKET, Key: "test/"};  
s3.deleteObject(params, function(err, data) {

});

If folder has no photo, delete function works well. But it contains photos, delete will not work.
Please help. Thank for all supports.

Upvotes: 4

Views: 8699

Answers (1)

Michael - sqlbot
Michael - sqlbot

Reputation: 179432

The problem here is a conceptual one, and starts at step 1.

This does not create a folder. It creates a placeholder object that the console will display as a folder.

An object named with a trailing "/" displays as a folder in the Amazon S3 console.

http://docs.aws.amazon.com/AmazonS3/latest/UG/FolderOperations.html

It's not necessary to do this -- creating objects with this key prefix will still cause the console to display a folder, even without creating this object. From the same page:

Amazon S3 has a flat structure with no hierarchy like you would see in a typical file system. However, for the sake of organizational simplicity, the Amazon S3 console supports the folder concept as a means of grouping objects. Amazon S3 does this by using key name prefixes for objects.

Since, at step 1, you are not actually creating a folder, it makes sense that removing the placeholder object also does not delete the folder.

Folders do not actually exist in S3 -- they're just used for display purposes in the console -- so objects cannot properly be said to be "in" folders. The only way to remove all the objects "in" a folder is to explicitly remove the objects individually. Similarly, the only way to rename a folder is to rename the objects in it... and the only way to rename an object is to make a copy of an the object with a new key and then delete the old object.

Upvotes: 9

Related Questions