1. const fs = require('fs');
  2. const readline = require('readline');
  3. /**
  4. * Pretty-prints the contents of a text file with retry logic.
  5. * @param {string} filePath The path to the text file.
  6. * @param {number} maxRetries The maximum number of retry attempts.
  7. */
  8. async function prettyPrintFile(filePath, maxRetries = 3) {
  9. let retries = 0;
  10. while (retries < maxRetries) {
  11. try {
  12. const fileContent = await fs.promises.readFile(filePath, 'utf8');
  13. // Use a simple regex for basic pretty-printing (line wrapping)
  14. const prettyText = fileContent.replace(/\n(?!\s)/g, '\n'); // Remove trailing newlines
  15. console.log(prettyText);
  16. return; // Exit the function if successful
  17. } catch (error) {
  18. retries++;
  19. console.error(`Error reading file (${filePath}): ${error.message}. Retry ${retries}/${maxRetries}...`);
  20. if (retries === maxRetries) {
  21. console.error(`Failed to read file (${filePath}) after ${maxRetries} retries.`);
  22. return; // Exit after max retries
  23. }
  24. // Optionally add a delay between retries
  25. await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
  26. }
  27. }
  28. }
  29. //Example usage (replace 'your_file.txt' with the actual file path)
  30. //prettyPrintFile('your_file.txt');

Add your comment