1. /**
  2. * Safely reads a file from a given path, with directory fallback.
  3. *
  4. * @param {string} filePath The path to the file.
  5. * @param {string} [defaultDir=''] The default directory to fallback to.
  6. * @returns {Promise<string>} A promise that resolves to the file content as a string,
  7. * or rejects if the file is not found.
  8. */
  9. async function readFileWithFallback(filePath, defaultDir = '') {
  10. try {
  11. // Attempt to read the file directly
  12. const fileContent = await fs.readFile(filePath, 'utf8');
  13. return fileContent;
  14. } catch (error) {
  15. // File not found or other error
  16. console.warn(`File not found at ${filePath}. Falling back to ${defaultDir}`);
  17. try {
  18. // Attempt to read from the default directory
  19. const defaultFilePath = `${defaultDir}/${filePath}`;
  20. const fileContent = await fs.readFile(defaultFilePath, 'utf8');
  21. return fileContent;
  22. } catch (error2) {
  23. // Default directory also not found
  24. console.error(`File not found at ${defaultFilePath}.`);
  25. throw error2; // Re-throw the error
  26. }
  27. }
  28. }
  29. //Example Usage (Requires 'fs' module, typically in Node.js)
  30. //const fs = require('fs'); // for Node.js environments only
  31. //Example with local file system
  32. /*
  33. async function main() {
  34. try {
  35. const content = await readFileWithFallback('data/myFile.txt', 'default_data');
  36. console.log(content);
  37. } catch (error) {
  38. console.error('Error:', error);
  39. }
  40. }
  41. main();
  42. */

Add your comment