const fs = require('fs');
const path = require('path');
/**
* Sorts records in a file with retry logic.
* @param {string} filePath - The path to the file.
* @param {function} parseRecord - Function to parse each line into a record. Returns null if parsing fails.
* @param {function} compareRecords - Function to compare two records.
* @param {object} options - Optional configuration.
* @param {number} options.maxRetries - Maximum number of retry attempts.
* @param {number} options.retryDelay - Delay in milliseconds between retries.
* @returns {Promise<Array<any>>} - A promise that resolves to the sorted array of records, or rejects on error.
*/
async function sortFileRecords(filePath, parseRecord, compareRecords, options = {}) {
const { maxRetries = 3, retryDelay = 1000 } = options;
let retries = 0;
while (retries < maxRetries) {
try {
const fileContent = fs.readFileSync(filePath, 'utf8'); // Read file content
const records = fileContent.split('\n').map(line => {
if (line.trim() === '') return null; // Skip empty lines
return parseRecord(line.trim()); // Parse each line into a record
}).filter(record => record !== null); //Remove null entries (failed parsing)
if (!records || records.length === 0) {
throw new Error("No records found in file or parsing failed.");
}
const sortedRecords = [...records].sort(compareRecords); // Create a copy to avoid modifying the original array
return sortedRecords;
} catch (error) {
retries++;
console.warn(`Error sorting file (attempt ${retries}/${maxRetries}): ${error.message}`);
if (retries < maxRetries) {
await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
} else {
throw error; // Re-throw the error after all retries have failed
}
}
}
}
module.exports = sortFileRecords;
Add your comment