How to get, upload and delete an object from s3 using aws-sdk for nodejs

How to get, upload and delete an object from s3 using aws-sdk for nodejs

Here's the TLDR.

  1. Create a file to where all the methods will be present.
// s3.js
import * as AWS from '@aws-sdk/client-s3';
const bucket = process.env.AWS_BUCKET_NAME;
const region = process.env.AWS_REGION;
const endpoint = process.env.AWS_ENDPOINT;
const client = new AWS.S3({ region, endpoint }) ;

export async function set(key, value) {
  try {
    return await client.putObject({
      Bucket: bucket,
      Key: key // `folder/image.webp`,
      Body: value, // buffer
      ContentType: 'image/webp'
    });
  } catch (e) {
    console.log('Store cache failed', e);
    throw e;
  }
}

export async function deleteFolder(path) {
  try {
    const listedObjects = await client.listObjectsV2({
      Bucket: bucket,
      Prefix: path // `folder`
    });
    if (!listedObjects.Contents || listedObjects.Contents.length === 0) return;
    const objs = listedObjects.Contents.map(obj => ({ Key: obj.Key }));
    await client.deleteObjects({
      Bucket: bucket,
      Delete: { Objects: objs }
    });
    if (listedObjects.IsTruncated) await clear(path); // if there are more files, then run it again
    console.log('Folder deleted', path);
    return;
  } catch (e) {
    console.log('Folder delete failed', e);
    throw e;
  }
}

export async function get(key) {
  try {
    const { Body } = await client.getObject({
      Bucket: bucket,
      Key: key // `folder/image.webp`
    });
    return Body;
  } catch (e) {
    return false;
  }
}
  1. Now in your controller or services, you can call these methods like so.
import fs from 'fs'
import path from 'path'
import { set, get, deleteFolder } from './s3.js'

async function controller() {
    // Save the file
    const file = fs.readFileSync(path.join(__dirname, 'image.webp'))
    await set("folder/image.webp", file)

    // Get the file
    const retrievedFile = await get("folder/image.webp")

    // Delete the folder
    await deleteFolder("folder")
}

Let me know if this works for you by commenting below. :)