node.js - My lambda is ending before my code completes and I'm not sure why - Stack Overflow

admin2025-05-01  0

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);

      });
    }
  });
};

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);

      });
    }
  });
};
Share Improve this question edited Jan 2 at 15:25 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Jan 2 at 15:19 DSATHDSATH 176 bronze badges 5
  • 3 First - you're ignoring the error. Start with printing something if you get the error. – stdunbar Commented Jan 2 at 15:22
  • 2 Why not use the promises API? Then you can flatten this all to a single async flow. – jonrsharpe Commented Jan 2 at 15:23
  • There's no Error and maybe I'll change it to promises after I figure out why this isn't working. – DSATH Commented Jan 2 at 15:26
  • It's not working because you're not using promises... – robertklep Commented Jan 2 at 15:40
  • OK I'll try promises then – DSATH Commented Jan 2 at 15:41
Add a comment  | 

1 Answer 1

Reset to default 2

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:

  • add await in front of this call
  • use the fs.writeFileSync function
转载请注明原文地址:http://anycun.com/QandA/1746110463a91811.html