node.jsamazon-s3

My lambda is ending before my code completes and I'm not sure why


My Lambda function is ending before all the code is run. I am not able to retrieve the converted file URL in this code. Why?

export const handler = async (event, context) => {
  // Geth the object from S3
  const bucket = "s3fileconverterinput";
  const key = event.Records[0].s3.object.key;

  var file = await getObject(bucket, key);
  console.log(file);
  var filePath = "/tmp/" + key;
  fs.writeFile(filePath, file, (err) => {
    if (err) {
    } else {
      console.log("File saved successfully!");
      convertapi.convert("pdf", { File: filePath }).then(function (result) {
        console.log("Converted file url: " + result.file.url);

      });
    }
  });
};

Solution

  • fs.writeFile is an asynchronous function. So I think this means that the handler ends without waiting for the writing function to resolve.

    You can either: