TypeError: Cannot read properties of undefined (reading 'pipe') in Production(Heroku server)

384 views Asked by At

I have the whole thing working locally but fails as soon as its on heroku server.

implementation

await pdf.create(pdfTemplate(data)).toStream(async function (err, stream) {
      await stream.pipe(fs.createWriteStream(`${req.body.phone}.pdf`));
      const params = {
        Bucket: "icon-path-bucket",
        Body: stream,
        Key: req.body.phone,
        contentType: "application/pdf"
      }

Error(in production)

2023-06-17T10:16:06.144530+00:00 app[web.1]:       await stream.pipe(fs.createWriteStream(`${req.body.phone}.pdf`));
2023-06-17T10:16:06.144530+00:00 app[web.1]:                    ^
2023-06-17T10:16:06.144530+00:00 app[web.1]: 
2023-06-17T10:16:06.144531+00:00 app[web.1]: TypeError: Cannot read properties of undefined (reading 'pipe')
1

There are 1 answers

0
Afolabi Opeyemi On

The html-pdf has been deprecated, so I was able to use puppeteer with the heroku build pack https://github.com/jontewks/puppeteer-heroku-buildpack. The implementation is below:

let browser = null

    try {
      browser = await puppeteer.launch({
        args: ['--no-sandbox'],
      });


      const page = await browser.newPage();

      await page.setContent(pdfTemplate(data));

      await page.pdf({ path: `${req.body.phone}.pdf` });

      console.log('PDF created successfully:', `${req.body.phone}.pdf`);

      console.log('PDF created successfully.');

      const fileData = fs.readFileSync(`${req.body.phone}.pdf`);
      const params = {
        Bucket: "icon-path-bucket",
        Body: fileData,
        Key: req.body.phone,
        ContentEncoding: "base64",
        contentType: "application/pdf"
      }

      // console.log("loooooooooooonnnng body", params.Body)

      s3.upload(params, function (err, data) {
        if (err) {
          console.log('Error uploading file:', err);
        } else {
          database.collection("MfmRegistration").insertOne(
            {
              firstName: req.body.fName,
              lastName: req.body.lName,
              email: req.body.email,
              filePath: `/api/download/${data.key}`
            },
            (err, data) => {
              res.redirect(`/success?message=${req.body.phone}`);
            }
          );
        }
      });

      // Close the browser
      await browser.close();

    } catch (err) {

      console.error('Error generating PDF:', err);

    } finally {

      // Close the browser
      if (browser !== null) {
        await browser.close();
      }

    }

Without the heroku build pack, the it will still fail on the server even if it works locally. Or the correct configuration for your server: see https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md#could-not-find-expected-browser-locally