/**
* Safely reads a file from a given path, with directory fallback.
*
* @param {string} filePath The path to the file.
* @param {string} [defaultDir=''] The default directory to fallback to.
* @returns {Promise<string>} A promise that resolves to the file content as a string,
* or rejects if the file is not found.
*/
async function readFileWithFallback(filePath, defaultDir = '') {
try {
// Attempt to read the file directly
const fileContent = await fs.readFile(filePath, 'utf8');
return fileContent;
} catch (error) {
// File not found or other error
console.warn(`File not found at ${filePath}. Falling back to ${defaultDir}`);
try {
// Attempt to read from the default directory
const defaultFilePath = `${defaultDir}/${filePath}`;
const fileContent = await fs.readFile(defaultFilePath, 'utf8');
return fileContent;
} catch (error2) {
// Default directory also not found
console.error(`File not found at ${defaultFilePath}.`);
throw error2; // Re-throw the error
}
}
}
//Example Usage (Requires 'fs' module, typically in Node.js)
//const fs = require('fs'); // for Node.js environments only
//Example with local file system
/*
async function main() {
try {
const content = await readFileWithFallback('data/myFile.txt', 'default_data');
console.log(content);
} catch (error) {
console.error('Error:', error);
}
}
main();
*/
Add your comment