Published on

How to Delete Multiple Files in AWS S3 using Node.js SDK

Authors

Sometimes you might want to delete multiple files in AWS S3 in one go.

For example, let's say your user has deleted their site and you need to delete all the files related to their account.

Here's a snippet on how to do it using Node.js using their SDK

Dependency

We'll need to install SDK. You can install it using the following command

npm install @aws-sdk/client-s3

And we'll need to have access keys as well.

export AWS_REGION="us-east-1" # Your region here
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_BUCKET_NAME="YOUR_BUCKET_NAME"

Deleting files using AWS SDK - Node.js

import { S3Client, DeleteObjectsCommand } from "@aws-sdk/client-s3";

const deleteMultipleFiles = async () => {
  const bucketName = process.env.AWS_BUCKET_NAME;

  const filesPathInS3 = ['example-path/profile.jpg', 'example-path/something.md']

  const params = {
        Bucket: bucketName,
        Delete: {
          Objects: filesPathInS3.map((key) => ({ Key: key })),
        },
  };
  

  const client = new S3Client({
    region: process.env.AWS_REGION,
    credentials: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    },
  });
  await client.send(new DeleteObjectsCommand(params));
};

Happy deleting files!