I have a lambda function (runtime Node.js 16.x) in which I need to list objects in a S3 bucket using Node.js. However for some reason, s3.listObjects() isn't doing anything. I can't seem to figure out why. The code is as follows:
const AWS = require('aws-sdk');
const https = require('https');
exports.handler = async (event, context, callback) => {
const awsOptions = {
region: "region"
};
const s3 = new AWS.S3(awsOptions);
const params = {
Bucket: 'bucketName',
Delimiter: '/',
Prefix: 'myPrefix/'
};
console.log("Before listing")
s3.listObjects(params, function(err, data) {
console.log("Listing objects")
if (err) console.log(err, err.stack); // an error occurred
else console.log(data);
});
console.log("After listing")
}
When testing the lambda with above code, it would only print
Before listing
After listing
It's as if listObjects() is never invoked. This is needed as part of a function to zip the s3 objects and upload into a bucket. If I hardcode the object keys, I can get the objects, create zip and upload the zip file without issue. But if I need to get the object keys via s3.ListObject() I'm facing the above problem where listObjects() not doing anything. Can someone please guid me to resolving the problem. Any help is much appreciated.
CodePudding user response:
TL;DR remove the async
keyword
You are mixing the non-async (= callback) handler pattern with the async (= return a promise) pattern.
A function with the async
keyword is an async handler. Your function's execution ends before your callback is finished. Remove the async
keyword and Lambda will wait until the event-loop is empty (until the callback is done) before exiting.