0
votes
var AWS = require('aws-sdk');
var s3 = new AWS.S3();

exports.handler = async (event) => {

            var bucketName = 'arn:aws:s3:::alessio77';
            var keyName = 'prova.txt';
            var content = 'This is a sample text file';
            var params = { 'Bucket': bucketName, 'Key': keyName, 'Body': content };
            s3.putObject(params, function (err, data) {
                console.log('entrato')
                if (err)
                    console.log(err)
                else
                    console.log("Successfully saved object to " + bucketName + "/" + keyName);
            });
};

this code neither write a file nor give me an error this is the log:

START RequestId: 7c93b1b9-73c1-4f18-9824-095bcbe292bf Version: $LATEST END RequestId: 7c93b1b9-73c1-4f18-9824-095bcbe292bf REPORT RequestId: 7c93b1b9-73c1-4f18-9824-095bcbe292bf Duration: 706.18 ms Billed Duration: 800 ms Memory Size: 128 MB Max Memory Used: 90 MB

1
Does the IAM role for your Lambda function have the necessary permissions to write to the S3 bucket? Are you seeing the console.log() output in the AWS console when you test your function? - Robert Lysik
@RobertLysik probably i don't have the needed permissions but why it doesn't notify me in the logs? in the log there isn't nothing - alex

1 Answers

3
votes

The s3.putObject is async and you need to wait for it. Most all aws api calls returns an AWS.Request which can return a promise. Here is a solution using await.

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

exports.handler = async (event) => {

            var bucketName = 'arn:aws:s3:::alessio77';
            var keyName = 'prova.txt';
            var content = 'This is a sample text file';
            var params = { 'Bucket': bucketName, 'Key': keyName, 'Body': content };
            try {
                console.log('entrato')
                const data = await s3.putObject(params).promise();
                console.log("Successfully saved object to " + bucketName + "/" + keyName);
                } catch (err) {
                     console.log(err)

                };
};