/**
* Gracefully handles text file maintenance tasks with input validation.
*
* @param {string} filePath - The path to the text file.
* @param {function} taskFunction - The function to execute on the file content.
* @returns {Promise<void>} - A promise that resolves when the task is complete or rejects on error.
*/
async function processTextFile(filePath, taskFunction) {
try {
// Check if the file exists
try {
await fs.access(filePath, fs.constants.F_OK); // Check if file exists
} catch (err) {
throw new Error(`File not found: ${filePath}`);
}
// Read the file content
const fileContent = await fs.readFile(filePath, 'utf8');
// Basic input validation: Check if the file content is not empty
if (!fileContent.trim()) {
throw new Error('File content is empty.');
}
// Execute the task function with the file content
await taskFunction(fileContent);
} catch (error) {
console.error(`Error processing file ${filePath}: ${error.message}`);
throw error; // Re-throw the error to allow the caller to handle it.
}
}
// Example usage (assuming you have 'fs' module available - e.g., from Node.js)
// npm install fs
const fs = require('fs');
/**
* Example task function: Convert text to uppercase
* @param {string} text - The text to convert.
* @returns {string} - The uppercase version of the text.
*/
async function convertToUppercase(text) {
console.log("Converting text to uppercase...");
const uppercaseText = text.toUpperCase();
console.log("Uppercase conversion complete.");
return uppercaseText;
}
// Example call
async function main() {
try {
await processTextFile('maintenance.txt', convertToUppercase);
console.log('File processing successful.');
} catch (error) {
console.error('File processing failed.');
}
}
//Create a dummy maintenance.txt for testing
fs.writeFileSync('maintenance.txt', 'This is a test file.');
main();
Add your comment