|
| 1 | +/* eslint-disable @typescript-eslint/explicit-member-accessibility */ |
| 2 | +/* eslint-disable @typescript-eslint/restrict-template-expressions */ |
| 3 | +/* eslint-disable @typescript-eslint/member-ordering */ |
| 4 | +/* eslint-disable no-console */ |
| 5 | +import * as fs from 'fs'; |
| 6 | +import * as cheerio from 'cheerio'; |
| 7 | + |
| 8 | +class HTMLParser { |
| 9 | + private parser: cheerio.CheerioAPI; |
| 10 | + |
| 11 | + // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility |
| 12 | + constructor(htmlFilePath: string) { |
| 13 | + // Load the HTML file and initialize cheerio |
| 14 | + const html = this.loadHTMLFromFile(htmlFilePath); |
| 15 | + this.parser = cheerio.load(html); |
| 16 | + } |
| 17 | + |
| 18 | + // Method to load HTML from a file |
| 19 | + private loadHTMLFromFile(filePath: string): string { |
| 20 | + try { |
| 21 | + return fs.readFileSync(filePath, 'utf8'); |
| 22 | + } catch (error) { |
| 23 | + console.error(`Error reading file from disk: ${error}`); |
| 24 | + throw error; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // Method to replace custom tags |
| 29 | + public replaceCustomTag(oldTag: string, newTag: string): void { |
| 30 | + this.parser(oldTag).each((_, element) => { |
| 31 | + const newElement = this.parser(`<${newTag}></${newTag}>`).html(this.parser(element).html()); |
| 32 | + this.parser(element).replaceWith(newElement); |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | + // Method to save modified HTML back to a file |
| 37 | + public saveToFile(outputFilePath: string): void { |
| 38 | + try { |
| 39 | + const modifiedHtml = this.parser.html(); |
| 40 | + fs.writeFileSync(outputFilePath, modifiedHtml); |
| 41 | + console.log(`Modified HTML saved to ${outputFilePath}`); |
| 42 | + } catch (error) { |
| 43 | + console.error(`Error writing file to disk: ${error}`); |
| 44 | + throw error; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Optional: Method to get the modified HTML as a string |
| 49 | + public getModifiedHTML(): string { |
| 50 | + return this.parser.html(); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +export default HTMLParser; |
0 commit comments