How to delete a folder on S3 with Node.js?

Sometimes, we want to delete a folder on S3 with Node.js.

In this article, we’ll look at how to delete a folder on S3 with Node.js.

How to delete a folder on S3 with Node.js?

To delete a folder on S3 with Node.js, we can use listObjectsV2 to list all objects in a bucket.

Then we call deleteObjects to delete the objects in the document.

For instance, we write

const emptyS3Directory = async (bucket, dir) => {
  const listParams = {
    Bucket: bucket,
    Prefix: dir
  };
  const listedObjects = await s3.listObjectsV2(listParams).promise();

  if (listedObjects.Contents.length === 0) {
    return;
  }

  const deleteParams = {
    Bucket: bucket,
    Delete: {
      Objects: []
    }
  };

  deleteParams.Delete.Objects = listedObjects.Contents.map(({
    Key
  }) => Key);
  await s3.deleteObjects(deleteParams).promise();
  if (listedObjects.IsTruncated) {
    await emptyS3Directory(bucket, dir);
  }
}

to define the emptyS3Directory that calls listObjectsV2 and promise to return a promise that returns all the file data in the bucket.

Then we define the deleteParams with the Delete.Objects property that we populate with

deleteParams.Delete.Objects = listedObjects.Contents.map(({
  Key
}) => Key);

to fill it with the keys to remove from the bucket.

And then we remove all the bucket contents with

await s3.deleteObjects(deleteParams).promise();

Finally, we check if the bucket is empty with listedObjects.IsTruncated.

And then we empty the bucket with

await emptyS3Directory(bucket, dir);

Conclusion

To delete a folder on S3 with Node.js, we can use listObjectsV2 to list all objects in a bucket.

Then we call deleteObjects to delete the objects in the document.