Skip to content

A fast, helpful, and open-source document parser

fix: wrap parse() processing in try/finally to prevent resource leaks

AdemBoukhris4570b02068c72f0
diff --git a/src/core/parser.ts b/src/core/parser.ts
index ddb35af..693615f 100644
--- a/src/core/parser.ts
+++ b/src/core/parser.ts
@@ -157,60 +157,60 @@ export class LiteParse {
log(`Loaded PDF with ${doc.numPages} pages`);
- // Extract pages
- const pages = await this.pdfEngine.extractAllPages(
- doc,
- this.config.maxPages,
- this.config.targetPages
- );
-
- // run BEFORE grid projection
- if (this.ocrEngine) {
- await this.runOCR(doc, pages, log);
- }
-
- // Process pages with complete grid projection (after OCR)
- const processedPages = projectPagesToGrid(pages, this.config);
+ try {
+ // Extract pages
+ const pages = await this.pdfEngine.extractAllPages(
+ doc,
+ this.config.maxPages,
+ this.config.targetPages
+ );
- // Build bounding boxes if enabled
- if (this.config.preciseBoundingBox) {
- for (const page of processedPages) {
- page.boundingBoxes = buildBoundingBoxes(page.textItems);
+ // run BEFORE grid projection
+ if (this.ocrEngine) {
+ await this.runOCR(doc, pages, log);
}
- }
- // Build final text
- const fullText = processedPages.map((p) => p.text).join("\n\n");
+ // Process pages with complete grid projection (after OCR)
+ const processedPages = projectPagesToGrid(pages, this.config);
- // Close PDF document
- await this.pdfEngine.close(doc);
+ // Build bounding boxes if enabled
+ if (this.config.preciseBoundingBox) {
+ for (const page of processedPages) {
+ page.boundingBoxes = buildBoundingBoxes(page.textItems);
+ }
+ }
- // Cleanup OCR engine if it's Tesseract (to free memory)
- if (this.ocrEngine && "terminate" in this.ocrEngine) {
- await (this.ocrEngine as TesseractEngine).terminate();
- }
+ // Build final text
+ const fullText = processedPages.map((p) => p.text).join("\n\n");
+
+ const result: ParseResult = {
+ pages: processedPages,
+ text: fullText,
+ };
+
+ // Format based on output format
+ switch (this.config.outputFormat) {
+ case "json":
+ result.json = JSON.parse(formatJSON(result));
+ break;
+ case "text":
+ // Already in text format
+ break;
+ }
- // Cleanup temporary conversion files
- if (needsCleanup && cleanupPath) {
- await cleanupConversionFiles(cleanupPath);
- }
+ return result;
+ } finally {
+ // Always release resources, even if processing throws
+ await this.pdfEngine.close(doc);
- const result: ParseResult = {
- pages: processedPages,
- text: fullText,
- };
+ if (this.ocrEngine && "terminate" in this.ocrEngine) {
+ await (this.ocrEngine as TesseractEngine).terminate();
+ }
- // Format based on output format
- switch (this.config.outputFormat) {
- case "json":
- result.json = JSON.parse(formatJSON(result));
- break;
- case "text":
- // Already in text format
- break;
+ if (needsCleanup && cleanupPath) {
+ await cleanupConversionFiles(cleanupPath);
+ }
}
-
- return result;
}
/**