by @kodeazy

How to check if a file exist in the S3 bucket or not

Home » javascript » How to check if a file exist in the S3 bucket or not

To check if the file is present in S3 bucket or not first we have to give access key id and secret access key to get access to AWS

AWS.config.update(
  {
    accessKeyId: "... your Access key Id ...",
    secretAccessKey: "... your secret key ...",
  }
);

Here in the below code getObject() function of s3 object checks if the file is present in the specific path which is specified in the key, if the file is present after executing the function, goes to else part of the code, If necessary we can download the file by taking the data variable and if we have appropriate permissions to download

If the file is not present goes to if part of the code and executes the statement.

var s3 = new AWS.S3();
s3.getObject(
 { Bucket: "BucketName", Key:"FileName" },
 function (error, data) {
   if (error) {
     console.log("File does not exist in S3 bucket");
   }
   else{
     console.log("File exist in S3 bucket");
   }
   });