loretoparisi
loretoparisi

Reputation: 16271

AWS NodeJs SDK cannot delete object

I'm trying to delete an object on my S3 bucket with the aws-sdk for Node.js using this s3.deleteObject api:

async function deleteObjectAsync(bucket, key) {
    try {
        var extras = {
            Bucket: bucket,
            Key: key
        };
        const data = await s3
            .deleteObject(extras)
            .promise();
        return data;
    } catch (err) {
        console.log(err);
    }
}//deleteObjectAsync

used like

(async (bucket, keys) => {
    for (const key of keys) {
        const result = await deleteObjectAsync(bucket, key);
        console.log(result);
    }
})(my_bucket, keys);

I get - as result - a DeleteMarker field and a VersionId:

{ DeleteMarker: true, VersionId: '2wMteXstTAn6e.rsTS6wHVSerXuUMNLXw' }

but the object does not seem to be deleted on the S3 bucket, but marked for deletion.

When using the Python api:

def delete_key(bucket, key):
    deleted = True
    try:
        s3 = boto3.client('s3')
        res = s3.delete_object(Bucket=bucket, Key=key)
    except Exception as e:
        print("deleted key:%s error:%s" % (key,e) )
        deleted = False
        pass
    return deleted

the file is immediately deleted. Why?

Upvotes: 0

Views: 1539

Answers (1)

Matheus Henrique Souza
Matheus Henrique Souza

Reputation: 146

To successfully delete and object from a versioned bucket is super simple, but the documentation isn't very clear on how one should do it.

From your own example above, here follows how you could do it:

async function deleteObjectAsync(bucket, key) {
  try {
    const params = {
      Bucket: bucket,
      Key: key,
      VersionId: 'null'
    };

    return await s3.deleteObject(params).promise();
  } catch (err) {
    console.error(err);
  }
}

The trick is to pass the 'null' string as VersionId when the object doesn't have a VersionId yet. When it does then you have to delete all the previous versions and then delete the 'null' version , which is the "original one".

Upvotes: 2

Related Questions