Skip to content

Commit

Permalink
Merge pull request #88 from mbpictures/hotfix/zombie-process-pdf
Browse files Browse the repository at this point in the history
hotfix/zombie-process-pdf
  • Loading branch information
mbpictures authored May 1, 2023
2 parents 2899358 + e8754e7 commit 59e75da
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 5 deletions.
59 changes: 59 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"notistack": "^2.0.5",
"paypal-checkout": "^4.0.336",
"pdf-lib": "^1.17.1",
"ps-node-promise-es6": "^0.0.1",
"puppeteer": "^19.8.2",
"qrcode": "^1.5.1",
"raw-body": "^2.5.1",
Expand Down
32 changes: 27 additions & 5 deletions src/lib/htmlToPdf.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import puppeteer from "puppeteer";
import ps from "ps-node-promise-es6";
import _ from "lodash";

export const generatePdf = async (html, options): Promise<Buffer> => {
const browser = await puppeteer.launch({
Expand All @@ -8,12 +10,32 @@ export const generatePdf = async (html, options): Promise<Buffer> => {
'--disable-setuid-sandbox',
]
});
const browserPID = browser.process().pid;
const page = await browser.newPage();
await page.setContent(html, {
waitUntil: 'networkidle0', // wait for page to load completely
});

const pdf = await page.pdf(options);
await browser.close();
let pdf;

try {
await page.setContent(html, {
waitUntil: 'networkidle0', // wait for page to load completely
});
pdf = await page.pdf(options);
} catch (e) {
throw new Error(e);
} finally {
await page.close();
await browser.close();
await killPID(browserPID);
}
return pdf;
}

const killPID = async (pid: number) => {
const psLookup = await ps.lookup({ pid: pid });
for (let proc of psLookup) {
if (_.has(proc, 'pid')) {
console.log(`Killing: ${proc.pid}`)
await ps.kill(proc.pid, 'SIGKILL');
}
}
}

0 comments on commit 59e75da

Please sign in to comment.