0
votes

I am trying to download a video file from S3 inside Lambda function. The idea is whenever the video files are uploaded into an S3 bucket the lambda function will be triggered. In Lambda function, I am downloading the video file and store it /tmp/ storage.

Here is my code,

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


exports.handler = function (event, context, callback) {
    var params = {
      Bucket: "Bucket_name",
      Key: event.Records[0].s3.object.key
    }
    console.log("key ", event.Records[0].s3.object.key);
    s3.getObject(params, function(err, data){   if (err) {
      console.error(err.code, "-", err.message);
      return callback(err);
    }
    fs.writeFile("/tmp/vid.mp4", data.Body, function(err){
      if(err)
        console.log(err.code, "-", err.message);
      return callback(err);
    });
    var stats = fs.statSync("/tmp/vid.mp4");
    console.log("size of the file ", stats["size"]);
  });
};

But I am not getting any error while executing this lambda function. But when I check the size of the file it gives 0. I don't have any idea about how to solve this. After downloading this file in lambda tmp storage I have to convert this video file into an audio file. So, please help me to find out the solution.

Thanks,

2

2 Answers

0
votes

Code is running asynchronously, console.log for the file size execute before writeFile finish. You need to put statSync inside the writeFile callback:

fs.writeFile("/tmp/vid.mp4", data.Body, function(err){
  if(err) console.log(err.code, "-", err.message);

  var stats = fs.statSync("/tmp/vid.mp4");
  console.log("size of the file ", stats["size"]); 
  return callback(err);
});
0
votes

The call to writeFile is asynchronous, i.e. the function "ends" immediately and the program execution continues with the statSync call. Replace it with writeFileSync.