Search code examples
node.jsaws-lambdahtml-to-pdf

Why is it not going inside the function? It only output "finish" and "start" on AWS Lambda


I'm doing a html to pdf function using the phantom-html-to-pdf on AWS Lambda with NodeJS. But I encountered a problem that did not go inside the function. The output only shows Start, Finish and Done is not shown which means it's not going in the function. What is the issue here?

var fs = require('fs')
var conversion = require("phantom-html-to-pdf")();

exports.handler = async (event) => {
    console.log("Start")
conversion({ html: "<h1>Hello World</h1>" }, 
  async(err, pdf) => {
  var output = fs.createWriteStream('output.pdf')
  console.log(pdf.logs);
  console.log(pdf.numberOfPages);
    // since pdf.stream is a node.js stream you can use it
    // to save the pdf to a file (like in this example) or to
    // respond an http request.
  pdf.stream.pipe(output);
  console.log("Done")
});

 console.log("Finish")

};

Solution

  • The problem is you have marked your lambda function as async which means your function should return a promise. In your case you are not returning a promise. So you have two choices here

    • Convert the conversion function from callback to promise based.
    • OR instead of marking the function async, add callback and execute that. something like this
    const fs = require("fs");
    const conversion = require("phantom-html-to-pdf")();
    
    exports.handler = (event, context, callback) => {
      console.log("Start");
      conversion({"html": "<h1>Hello World</h1>"},
        // eslint-disable-next-line handle-callback-err
        async (err, pdf) => {
          const output = fs.createWriteStream("output.pdf");
          console.log(pdf.logs);
          console.log(pdf.numberOfPages);
          // since pdf.stream is a node.js stream you can use it
          // to save the pdf to a file (like in this example) or to
          // respond an http request.
          pdf.stream.pipe(output);
          console.log("Done");
          callback(null, "done");
        });
    };