Solution 1 :

Since printPDF is an async function returning Promise, you need to wait for it to finish, with then for example:

const getReviewPage = (req, res) => {
  printPDF().then(() => res.sendFile(`${__dirname}/form.html`)
}

Problem :

I am trying to convert an html web page into a pdf file by using puppeteer. It is converting the html web page into pdf file but the problem is that, page.goto is not stopping after its job is done. When this happens, the terminal I run this localhost server from becomes a little unresponsive. I also deployed it on heroku but when I visit the url, the server responds me with error code 503 and it does not convert to pdf there.

let printPDF = async () => {
  try {
    const browser = await puppeteer.launch({ headless: true});
    const page = await browser.newPage();
    await page.goto('http://localhost:3000/preview')
    await page.pdf({ format: 'A4' , path: `${__dirname}/contact.pdf`, printBackground: true});

    await page.close();
    await browser.close();
    console.log("repeat") //logging to see its repetition
  }

  catch (error) {
    await page.close();
    await browser.close();
  }
}

getReviewPage = ((req, res) => {
    printPDF()
    res.sendFile(`${__dirname}/form.html`)
})

app.route('/preview').get(getReviewPage);

Comments

Comment posted by Abhi

It solved the problem. Now I’ll always remember that an async function returns a Promise. I am still learning. Thank you, sire.

By