pinale
pinale

Reputation: 2214

aws lambda write a file on s3 - javascript

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

Upvotes: 1

Views: 2104

Answers (1)

WaltDe
WaltDe

Reputation: 1842

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)

                };
};

Upvotes: 4

Related Questions