简体   繁体   中英

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?

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'})
    }

};

AWS SDK可以返回承诺,只需将.promise()添加到您的函数中即可。

s3.listObjectsV2(params).promise();

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