read-file.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import fs from 'node:fs'
  2. import path from 'node:path'
  3. import { PDFParse } from 'pdf-parse'
  4. import AdmZip from 'adm-zip'
  5. import { setTimeout } from 'node:timers/promises'
  6. const MAX_ATTEMPTS = 15
  7. const POLL_INTERVAL = 500
  8. type ReadFileInZipArgs = {
  9. pathToZip: string
  10. fileToRead: string
  11. }
  12. export async function readFileInZip({
  13. pathToZip,
  14. fileToRead,
  15. }: ReadFileInZipArgs) {
  16. let attempt = 0
  17. while (attempt < MAX_ATTEMPTS) {
  18. if (fs.existsSync(pathToZip)) {
  19. const zip = new AdmZip(path.resolve(pathToZip))
  20. const entry = zip
  21. .getEntries()
  22. .find(entry => entry.entryName === fileToRead)
  23. if (entry) {
  24. return entry.getData().toString('utf8')
  25. } else {
  26. throw new Error(`${fileToRead} not found in ${pathToZip}`)
  27. }
  28. }
  29. await setTimeout(POLL_INTERVAL)
  30. attempt++
  31. }
  32. throw new Error(`${pathToZip} not found`)
  33. }
  34. export async function readPdf(file: string) {
  35. let attempt = 0
  36. while (attempt < MAX_ATTEMPTS) {
  37. if (fs.existsSync(file)) {
  38. const dataBuffer = fs.readFileSync(path.resolve(file))
  39. const parser = new PDFParse({ data: dataBuffer })
  40. try {
  41. const result = await parser.getText()
  42. return result.text
  43. } catch (error) {
  44. console.error('PDF parsing failed:', error)
  45. } finally {
  46. await parser.destroy()
  47. }
  48. }
  49. await setTimeout(POLL_INTERVAL)
  50. attempt++
  51. }
  52. throw new Error(`${file} not found`)
  53. }