Categories
JavaScript Answers

How to determine if object exists AWS S3 Node.JS SDK?

Spread the love

To determine if object exists AWS S3 Node.JS SDK, we call the headObject method.

For instance, we write

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

const params = {
  Bucket: s3BucketName,
  Key: "filename",
};
try {
  await s3.headObject(params).promise();
  console.log("File Found in S3");
} catch (err) {
  console.log("File not Found ERROR : " + err.code);
}

to call headObject with the params with the bucket name and key to check if the object with the key exists in the Bucket.

And we call promise to make it return a promise.

If it doesn’t throw an error, then the object is found.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *