Skip to content

Commit e726839

Browse files
committed
improve PDF answer sync
1 parent fd13a66 commit e726839

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

pdf-service.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ app.use(bodyParser.urlencoded({
1313
parameterLimit: 1000,
1414
})); // support encoded bodies
1515

16+
const storagePath = path.join(__dirname, 'storage');
17+
if (!fs.existsSync(storagePath)) {
18+
fs.mkdirSync(storagePath);
19+
}
20+
1621
let port = 3000;
1722
let calls = {
1823
health: 0,
@@ -21,7 +26,6 @@ let calls = {
2126
};
2227
let isReady = false;
2328
let browser = null;
24-
let storagePath = 'storage';
2529

2630
app.get('/health', (req, res) => {
2731
calls.health++;
@@ -85,10 +89,13 @@ function deliverPdfFile(res, pdfFilePath) {
8589
res.setHeader('Content-Length', fs.statSync(pdfFilePath).size);
8690
res.setHeader('Content-Type', 'application/pdf');
8791
res.setHeader('Content-Disposition', 'inline');
88-
reader.pipe(res);
89-
90-
console.log('deliverPdfFile: going to remove file', pdfFilePath);
91-
fs.unlinkSync(pdfFilePath);
92+
reader.on('open', () => {
93+
reader.pipe(res);
94+
});
95+
reader.on('close', () => {
96+
console.log('deliverPdfFile: going to remove file', pdfFilePath);
97+
fs.unlinkSync(pdfFilePath);
98+
});
9299
}
93100

94101
async function generatePdf(url, media) {
@@ -110,11 +117,7 @@ async function generatePdf(url, media) {
110117
});
111118

112119
let filename = md5(url) + '.pdf';
113-
const pdfFolder = path.join(__dirname, storagePath);
114-
if (!fs.existsSync(pdfFolder)) {
115-
fs.mkdirSync(pdfFolder);
116-
}
117-
const pdfFilePath = path.join(pdfFolder, filename);
120+
const pdfFilePath = path.join(storagePath, filename);
118121

119122
console.log('generatePdf: generate PDF', pdfFilePath);
120123
await page.pdf({

0 commit comments

Comments
 (0)