1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Sorts records in a file with retry logic.
  5. * @param {string} filePath - The path to the file.
  6. * @param {function} parseRecord - Function to parse each line into a record. Returns null if parsing fails.
  7. * @param {function} compareRecords - Function to compare two records.
  8. * @param {object} options - Optional configuration.
  9. * @param {number} options.maxRetries - Maximum number of retry attempts.
  10. * @param {number} options.retryDelay - Delay in milliseconds between retries.
  11. * @returns {Promise<Array<any>>} - A promise that resolves to the sorted array of records, or rejects on error.
  12. */
  13. async function sortFileRecords(filePath, parseRecord, compareRecords, options = {}) {
  14. const { maxRetries = 3, retryDelay = 1000 } = options;
  15. let retries = 0;
  16. while (retries < maxRetries) {
  17. try {
  18. const fileContent = fs.readFileSync(filePath, 'utf8'); // Read file content
  19. const records = fileContent.split('\n').map(line => {
  20. if (line.trim() === '') return null; // Skip empty lines
  21. return parseRecord(line.trim()); // Parse each line into a record
  22. }).filter(record => record !== null); //Remove null entries (failed parsing)
  23. if (!records || records.length === 0) {
  24. throw new Error("No records found in file or parsing failed.");
  25. }
  26. const sortedRecords = [...records].sort(compareRecords); // Create a copy to avoid modifying the original array
  27. return sortedRecords;
  28. } catch (error) {
  29. retries++;
  30. console.warn(`Error sorting file (attempt ${retries}/${maxRetries}): ${error.message}`);
  31. if (retries < maxRetries) {
  32. await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
  33. } else {
  34. throw error; // Re-throw the error after all retries have failed
  35. }
  36. }
  37. }
  38. }
  39. module.exports = sortFileRecords;

Add your comment