Home > Back-end >  Can't upload files from LAMBDA to S3
Can't upload files from LAMBDA to S3

Time:11-03

I tested on my localhost, then checked on s3 and saw that there was a new file created. But when testing on Lambda, although there is no error, there is no file on S3. The log of s3.upload(params).promise() is also not displayed.

var fs = require('fs');
var AWS = require('aws-sdk');
exports.handler = async (event, context, callback) => {
    context.callbackWaitsForEmptyEventLoop = false
    try {
        AWS.config.update({
            accessKeyId: accessKeyId,
            secretAccessKey: secretAccessKey
        });
        
        var s3 = new AWS.S3();
        var path = 'myfile.txt';
        var file_buffer =  fs.readFileSync(path);

        console.log(file_buffer);
        var params = {
            Bucket: 'bucket-dev',
            Key: '2222.txt',
            Body: file_buffer
        };
        console.log("1111");
        s3.upload(params).promise()
            .then(function(data) {
                console.log("Successfully uploaded to");
                callback(null, "All Good");
            })
            .catch(function(err) {
                console.error(err, err.stack);
                callback(err);
            });
        console.log("2222");
       return context.logStreamName
    } catch (err) {
        console.log(err);
        callback(err);
    }
}

Thanks

CodePudding user response:

Try not to mix and match async and callback. Something like this might be closer to what you want...

var fs = require("fs");
var AWS = require("aws-sdk");

exports.handler = async (event, context) => {
  AWS.config.update({
    accessKeyId,
    secretAccessKey,
  });

  const s3 = new AWS.S3();
  const path = "myfile.txt";
  const file_buffer = fs.readFileSync(path);
  const params = {
    Bucket: "bucket-dev",
    Key: "2222.txt",
    Body: file_buffer,
  };
  console.log("1111");
  const res = await s3.upload(params).promise();
  console.log("Successfully uploaded", res);
  return "All good";
};
  • Related