简体   繁体   中英

AWS Lambda - Unable to perform an action if object exists in S3

I am writing a lambda function in NodeJs where i want to check if a file exists in S3. If the file exists I return "A", otherwise I return "B". I am using S3.HeadObject to get object metadata as a promise.

exports.handler = async (event, context, callback) => {
var params = {
    Bucket: "BucketName", 
    Key: "ObjectName"
};

const response = s3.headObject(params).promise();

I am able to get the response, but I am unable to check if the file exists or not. I first tried if/else clause

 response.then(function(result) {
  const type = result['ContentType'];
  if(type == 'image/jpeg') {
      return "URL1"
  } else {
      return "URL2"
  }
}); 

But, i never get URL1 or URL2 returned, the lambda returns null. Going through few other SO posts, I found another way of doing this:

s3.headObject(params, function(err, data) {
 if (err) {
  console.log(err, err.stack);
  return;
 }
 console.log(data)
});

But, this way i do not get any response at all. The loggers do not print anything.

Could anybody please advise what am I doing wrong? I want to return a specific URL based on the availability of files in S3. If JPG is present, return JPG url. Otherwise return PNG url.

Thanks!

I tested the following one with exist/not-exist cases, prints true/false depending on the existence. I didn't try to get content or other meta data (just availability) since you mentioned

I want to return a specific URL based on the availability of files in S3

let AWS = require('aws-sdk');
let S3 = new AWS.S3();

exports.handler = async(event, context, callback) => {
    let exist = await get();
    console.log(exist);
    // your exist checks
};

async function get() {
    let exist = true;
    let params = {
        Bucket: "your-bucket-name",
        Key: 'your-key'
    };

    try {
        await S3.headObject(params).promise();
    } catch (err) {
        exist = false;
    }

    return exist;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM