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



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 is below:
Solution 1:
Deleting folder directly.

var key='level/folder1/folder2/';
var strReturn;
        var params = {Bucket: MyBucket};
        var s3 = new AWS.S3(params);
            Bucket: MyBucket,
            Key: key
        }, function (err, data) {

            console.log('error:'+err+' data:'+JSON.stringify(data));

Actually, I have a lot of files under folder2. I can delete single file from folder2 if I define key like this:
var key=’level/folder1/folder2/file1.txt’, but it didn’t work when I deleted a folder(key=’level/folder1/folder2/’).
Solution 2:
I tried to set expiration to an object when I uploaded this file or folder to s3. code is below:

                Bucket: Camera_Bucket,
                Key: key,
                Expires: 60 

But it didn’t either. After finishing uploading, I checked the properties of that file. it showed there was nothing value for expiry date:

Expiry Date:none
Expiration Rule:N/A

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


You can use aws-sdk module for deleting folder. Because you can only delete a folder when it is empty, you should first delete the files in it. I’m doing it like this :

function emptyBucket(bucketName,callback){
  var params = {
    Bucket: bucketName,
    Prefix: 'folder/'

  s3.listObjects(params, function(err, data) {
    if (err) return callback(err);

    if (data.Contents.length == 0) callback();

    params = {Bucket: bucketName};
    params.Delete = {Objects:[]};
    data.Contents.forEach(function(content) {
      params.Delete.Objects.push({Key: content.Key});

    s3.deleteObjects(params, function(err, data) {
      if (err) return callback(err);
      if (data.IsTruncated) {
        emptyBucket(bucketName, callback);
      } else {

Answered By – Sangbeom Han

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More