Lambda function to S3 instance not uploading

Viewed 34

The code below allows me to update a image or video to S3 from command line as a node js but not from lamba function, would it be possible to know why? Lambda function does not return any error it just doesn't upload the file.

const fs = require('fs');
const http = require('http');
const AWS = require('aws-sdk');
const request = require('request');

function uploadFile(data, fileName)
{
    const s3 = new AWS.S3();


     console.log(data)
     const params = {
         Bucket: 'trakbucket', // pass your bucket name
         Key: fileName, // file will be saved as testBucket/contacts.csv
         Body: JSON.stringify(data, null, 2)
     };
     s3.upload(params, function(s3Err, data) {
         if (s3Err) throw s3Err
         console.log(`File uploaded successfully at ${data.Location}`)
  });
};


exports.handler = async (event) => {
    let videoURL = "http://farm4.static.flickr.com/3123/2341623661_7c99f48bbf_m.jpg";
    let file_name = "video.mp4"
    let file_path = "/tmp/" +  file_name
    request.get(videoURL, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = body;
            console.log(data)
            uploadFile(data, file_name)
            console.log("End")
        }
    });
};
1 Answers

Since you are using async handler I think the issue is that your function completes before the handler's body has a chance to run.

One way to rectify this is through the use of Promise as shown in AWS docs. For example:

exports.handler = async (event) => {

    const promise = new Promise(function(resolve, reject) {

        let videoURL = "http://farm4.static.flickr.com/3123/2341623661_7c99f48bbf_m.jpg";
        let file_name = "video.mp4"
        let file_path = "/tmp/" +  file_name
        request.get(videoURL, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var data = body;
                console.log(data)
                uploadFile(data, file_name)
                console.log("End")
            }
        });

      })

  return promise;       
};

The above changes are exemplary only, thus probably some adjustments will be still needed.

Related