1. /**
  2. * Gracefully handles text file maintenance tasks with input validation.
  3. *
  4. * @param {string} filePath - The path to the text file.
  5. * @param {function} taskFunction - The function to execute on the file content.
  6. * @returns {Promise<void>} - A promise that resolves when the task is complete or rejects on error.
  7. */
  8. async function processTextFile(filePath, taskFunction) {
  9. try {
  10. // Check if the file exists
  11. try {
  12. await fs.access(filePath, fs.constants.F_OK); // Check if file exists
  13. } catch (err) {
  14. throw new Error(`File not found: ${filePath}`);
  15. }
  16. // Read the file content
  17. const fileContent = await fs.readFile(filePath, 'utf8');
  18. // Basic input validation: Check if the file content is not empty
  19. if (!fileContent.trim()) {
  20. throw new Error('File content is empty.');
  21. }
  22. // Execute the task function with the file content
  23. await taskFunction(fileContent);
  24. } catch (error) {
  25. console.error(`Error processing file ${filePath}: ${error.message}`);
  26. throw error; // Re-throw the error to allow the caller to handle it.
  27. }
  28. }
  29. // Example usage (assuming you have 'fs' module available - e.g., from Node.js)
  30. // npm install fs
  31. const fs = require('fs');
  32. /**
  33. * Example task function: Convert text to uppercase
  34. * @param {string} text - The text to convert.
  35. * @returns {string} - The uppercase version of the text.
  36. */
  37. async function convertToUppercase(text) {
  38. console.log("Converting text to uppercase...");
  39. const uppercaseText = text.toUpperCase();
  40. console.log("Uppercase conversion complete.");
  41. return uppercaseText;
  42. }
  43. // Example call
  44. async function main() {
  45. try {
  46. await processTextFile('maintenance.txt', convertToUppercase);
  47. console.log('File processing successful.');
  48. } catch (error) {
  49. console.error('File processing failed.');
  50. }
  51. }
  52. //Create a dummy maintenance.txt for testing
  53. fs.writeFileSync('maintenance.txt', 'This is a test file.');
  54. main();

Add your comment