node.jsamazon-web-servicesfunctionamazon-s3aws-sdk

This simple AWS function to delete a directory is not working


I am writing this simple code to delete a directory that is asked to be deleted

here is the function regarding deleting it

async function deleteProject (data) {
    const params = {
        Bucket: process.env.S3_BUCKET,
        Key: data,
    };
    try {
        await s3.deleteObject(params).promise();
        // console.log(`Successfully deleted ${key} from S3`); // Debug log
        return { success: true };
    } catch (error) {
        // console.error(`Error deleting ${key} from S3:`, error.message); // Debug log
        return { success: false, message: error.message };
    }
}

now this function is getting the key,(debugged it) and this function isnt producing any errors but the function isnt deleting the folder it is asked to

Kindly help!


Solution

  • The deleteObject call deletes one object. It won't delete multiple objects under a given prefix. You have to enumerate the objects under that prefix/directory using listObjectsV2 and delete them all using deleteObjects, up to 1000 at a time.

    Also note that if you call deleteObject on a non-existent object, that call will succeed. So, in your case it's likely that you are calling deleteObject("folder1/") and that call is succeeding but deleting nothing, unless there happens to be an object with the key folder1/ in which case that object will be deleted (but it won't delete anything else below folder1/).

    S3 object storage is not like a regular file system (e.g. NTFS or FAT32). A 'directory' doesn't need to exist for there to be files that are logically in that directory.