1. const fs = require('fs').promises;
  2. const path = require('path');
  3. /**
  4. * Imports data from directories with fixed retry intervals.
  5. * @param {string[]} directories An array of directory paths.
  6. * @param {number} retryIntervalMs The retry interval in milliseconds.
  7. * @returns {Promise<object>} An object containing the imported data. Returns an empty object if no directories are provided.
  8. */
  9. async function importDataFromDirectories(directories, retryIntervalMs) {
  10. if (!directories || directories.length === 0) {
  11. return {}; // Handle empty directory list
  12. }
  13. const importedData = {};
  14. for (const directory of directories) {
  15. try {
  16. const files = await fs.readdir(directory); // Read directory contents
  17. importedData[directory] = await processDirectory(directory, files);
  18. } catch (err) {
  19. console.error(`Error reading directory ${directory}:`, err);
  20. await delay(retryIntervalMs); // Retry after interval
  21. try {
  22. const files = await fs.readdir(directory); // Retry read
  23. importedData[directory] = await processDirectory(directory, files);
  24. } catch (retryErr) {
  25. console.error(`Error reading directory ${directory} after retry:`, retryErr);
  26. importedData[directory] = null; // Mark as failed
  27. }
  28. }
  29. }
  30. return importedData;
  31. }
  32. /**
  33. * Processes a single directory and its files.
  34. * @param {string} directoryPath The path to the directory.
  35. * @param {string[]} files An array of file names in the directory.
  36. * @returns {object} An object containing the processed data for the directory.
  37. */
  38. async function processDirectory(directoryPath, files) {
  39. const data = {};
  40. for (const file of files) {
  41. const filePath = path.join(directoryPath, file);
  42. try {
  43. const fileContent = await fs.readFile(filePath, 'utf8'); // Read file content
  44. data[file] = fileContent; // Store file content
  45. } catch (err) {
  46. console.error(`Error reading file ${filePath}:`, err);
  47. data[file] = null; // Mark as failed
  48. }
  49. }
  50. return data;
  51. }
  52. /**
  53. * Delays execution for a specified number of milliseconds.
  54. * @param {number} ms The delay in milliseconds.
  55. * @returns {Promise<void>} A promise that resolves after the delay.
  56. */
  57. function delay(ms) {
  58. return new Promise(resolve => setTimeout(resolve, ms));
  59. }
  60. module.exports = importDataFromDirectories;

Add your comment