80

I want to delete a file from Amazon S3 using JavaScript. I have already uploaded the file using JavaScript. How can I delete it?

starball
  • 20,030
  • 7
  • 43
  • 238
user3335960
  • 835
  • 1
  • 6
  • 6

8 Answers8

140

You can use the JS method from S3:

var AWS = require('aws-sdk');

AWS.config.loadFromPath('./credentials-ehl.json');

var s3 = new AWS.S3();
var params = {  Bucket: 'your bucket', Key: 'your object' };

s3.deleteObject(params, function(err, data) {
  if (err) console.log(err, err.stack);  // error
  else     console.log();                 // deleted
});

Be aware that S3 never returns the object if it has been deleted. You have to check it before or after with getobject, headobject, waitfor, etc

Shafkhan
  • 456
  • 4
  • 19
jlalcazar
  • 1,501
  • 1
  • 8
  • 4
  • 1
    S3 returns DeleteMarker and VersionId. – Rohit Jun 11 '15 at 13:54
  • @Rohit that's because you've got a versioned bucket. You need to delete all object versions (including any delete markers) in order to remove the object entirely. – AJB Oct 22 '16 at 04:20
  • 23
    If using async/await, you must add `.promise()` at last. Ex: `await s3.deleteObject(params).promise()` – Thai Ha Feb 23 '19 at 15:45
  • @AJB Is there any way to delete all versions of a file at once? or it should be carried out version by version? – shwz May 07 '19 at 07:18
  • 1
    @shwz There's no method to delete all versions (and deleteMarkers) at the same time. I believe that is by design to make it impossible to accidentally delete objects. You need to first gather all the versionIDs and deleteMarkers and then call deleteObject on all of them using either a batch or a loop. – AJB May 08 '19 at 22:02
  • @AJB Yes, thanks for the reply. I gethered all the versions and passed to `deleteObjects` method – shwz May 09 '19 at 07:54
41

You can use construction like this:

var params = {
  Bucket: 'yourBucketName',
  Key: 'fileName'
  /* 
     where value for 'Key' equals 'pathName1/pathName2/.../pathNameN/fileName.ext'
     - full path name to your file without '/' at the beginning
  */
};

s3.deleteObject(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

And don't forget to wrap it to the Promise.

Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
Vitalii Andrusishyn
  • 3,984
  • 1
  • 25
  • 31
  • this deletes a single file... I've used it and it's functional – Steve Nginyo Aug 03 '20 at 09:18
  • 2
    the response is the same though even when the object does not exist – Steve Nginyo Aug 03 '20 at 09:19
  • I know I'm super late to this, but this solved my problem... and I'm not sure why. Deleting was working for me using the following syntax: "const deleteRes = await s3.deleteObject({Bucket: 'some-bucket', Key: req.query.someKey});" before I started organizing my objects into folders when this stopped working. Switching to: "s3.deleteObject({Bucket: 'some-bucket', Key: req.query.someKey}, function(err, data){});" solved this error but I have no idea why. Any thoughts? – Rharris389 Jun 09 '21 at 19:47
36

Before deleting the file you have to check the 1) file whether it is in the bucket because If the file is not available in the bucket and using deleteObject API this doesn't throw any error 2)CORS Configuration of the bucket. By using headObject API gives the file status in the bucket.

AWS.config.update({
        accessKeyId: "*****",
        secretAccessKey: "****",
        region: region,
        version: "****"
    });
const s3 = new AWS.S3();

const params = {
        Bucket: s3BucketName,
        Key: "filename" //if any sub folder-> path/of/the/folder.ext
}
try {
    await s3.headObject(params).promise()
    console.log("File Found in S3")
    try {
        await s3.deleteObject(params).promise()
        console.log("file deleted Successfully")
    }
    catch (err) {
         console.log("ERROR in file Deleting : " + JSON.stringify(err))
    }
} catch (err) {
        console.log("File not Found ERROR : " + err.code)
}

As params are constant, the best way to use it with const. If the file is not found in the s3 it throws the error NotFound : null.

If you want to apply any operations in the bucket, you have to change the permissions of CORS Configuration in the respective bucket in the AWS. For changing permissions Bucket->permission->CORS Configuration and Add this code.

<CORSConfiguration>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

for more information about CROS Configuration : https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html

banoth ravinder
  • 1,314
  • 15
  • 18
27

You can use deleteObjects API to delete multiple objects at once instead of calling API for each key to delete. Helps save time and network bandwidth.

You can do following-

var deleteParam = {
    Bucket: 'bucket-name',
    Delete: {
        Objects: [
            {Key: 'a.txt'},
            {Key: 'b.txt'},
            {Key: 'c.txt'}
        ]
    }
};    
s3.deleteObjects(deleteParam, function(err, data) {
    if (err) console.log(err, err.stack);
    else console.log('delete', data);
});

For reference see - https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObjects-property

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
10

You can follow this GitHub gist link https://gist.github.com/jeonghwan-kim/9597478.

delete-aws-s3.js:

var aws = require('aws-sdk');
var BUCKET = 'node-sdk-sample-7271';
aws.config.loadFromPath(require('path').join(__dirname, './aws-config.json'));
var s3 = new aws.S3();

var params = {
  Bucket: 'node-sdk-sample-7271', 
  Delete: { // required
    Objects: [ // required
      {
        Key: 'foo.jpg' // required
      },
      {
        Key: 'sample-image--10.jpg'
      }
    ],
  },
};

s3.deleteObjects(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});
karel
  • 5,489
  • 46
  • 45
  • 50
iamsohel
  • 387
  • 3
  • 7
5

Very straight forward

At first, create an instance of s3 and configure it with credentials

const S3 = require('aws-sdk').S3;

const s3 = new S3({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION
});

Afterward, follow the docs


 var params = {
  Bucket: "ExampleBucket", 
  Key: "HappyFace.jpg"
 };
 s3.deleteObject(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
   /*
   data = {
   }
   */
 });
MD SHAYON
  • 7,001
  • 45
  • 38
1

First, you need to create a new instance of the AWS S3.

Here's how you can do it:

const s3 = new AWS.S3({
  accessKeyId: AWS_ACCESS_KEY_ID,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
});

Replace AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY with your AWS Access Key Id and AWS Secret Access Key.

Using this S3 instance, delete a object:

export const s3DeleteObject = (filename: string) => {
  return new Promise((resolve, reject) => {
    const params = {
      Key: filename,
      Bucket: AWS_BUCKET_NAME,
    };

    s3.deleteObject(params, (err: any, data: any) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

Then call the function where it is needed:

await s3DeleteObject("fileName");

Using @aws-sdk/client-s3 the updated docs is here

Kayes
  • 51
  • 6
  • Using `@aws-sdk/client-s3` the updated docs is [here](https://stackoverflow.com/a/76961504/19059203) – Kayes Aug 24 '23 at 05:59
0

As of 2023 s3 will be retiring the v2

To solve the issue using v3 use

const client = new S3Client({});

export const main = async () => {
  const command = new DeleteObjectCommand({
    Bucket: "test-bucket",
    Key: "test-key.txt",
  });

  try {
    const response = await client.send(command);
    console.log(response);
  } catch (err) {
    console.error(err);
  }
};

You should try to avoid access key and secret, but if you really have to do it, new format is

new S3Client({
      credentials: {
        accessKeyId: process.env.S3_ACCESS_KEY_ID,
        secretAccessKey: process.env.S3_SECRET_ACCESS_KEY
      },
      region: process.env.S3_REGION
});

Just to add. You shouldn't run this code client side. If you do you risk giving access to a lot more resources than you should.

What you should use instead is pre-signed URLs. You can generate them on backend for specific files and then send them to front end.

Read more:

https://docs.aws.amazon.com/AmazonS3/latest/userguide/example_s3_DeleteObject_section.html

Maciej Paprocki
  • 1,230
  • 20
  • 29