Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS S3 ListObjects in Node.js Lambda Function

I am attempting to list an S3 bucket from within my node.js (8.10) lambda function.

When I run the function below (in Lambda), I see "Checkpoint 1" and "Checkpoint 2" in my logs, but I don't see any logging from the listObjectsV2 call, neither error nor data. My timeout is set to 10 seconds and I am not seeing any log entries for timeouts, either. I think I may missing something about using asynchronous functions in lambda?

const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    // console.log('Received event:', JSON.stringify(event, null, 2));

    var params = { 
        Bucket: 'bucket-name'
    }

    console.log("Checkpoint 1");

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


    console.log("Checkpoint 2");

};

Can someone point me in the right direction for finding my error here?

like image 838
Rick Free Avatar asked Dec 17 '22 21:12

Rick Free


1 Answers

Not only you need to return a promise, you also need to await on it, otherwise it has no effect. This is because your handler is async, meaning it will return a promise anyways. This means that if you don't await on the code you want to execute, it's very likely that Lambda will terminate before the promise is ever resolved.

Your code should look like this:

const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    // console.log('Received event:', JSON.stringify(event, null, 2));

    var params = { 
        Bucket: 'bucket-name'
    }

    console.log("Checkpoint 1");

    let s3Objects

    try {
       s3Objects = await s3.listObjectsV2(params).promise();
       console.log(s3Objects)
    } catch (e) {
       console.log(e)
    }


    console.log("Checkpoint 2");

    // Assuming you're using API Gateway
    return {
        statusCode: 200,
        body: JSON.stringify(s3Objects || {message: 'No objects found in s3 bucket'})
    }

};
like image 62
Thales Minussi Avatar answered Jan 18 '23 08:01

Thales Minussi