Reputation: 872
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!
Upvotes: 2
Views: 1186
Reputation: 9624
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;
}
Upvotes: 5