1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Syncs resources between datasets based on a configuration file.
  5. * @param {string} configPath Path to the configuration file.
  6. */
  7. async function syncDatasets(configPath) {
  8. try {
  9. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  10. if (!config.datasets || !Array.isArray(config.datasets)) {
  11. console.error("Invalid config format: 'datasets' must be an array.");
  12. return;
  13. }
  14. for (const datasetName in config.datasets) {
  15. if (!config.datasets.hasOwnProperty(datasetName)) continue;
  16. const datasetConfig = config.datasets[datasetName];
  17. if (!datasetConfig.source || !datasetConfig.target) {
  18. console.warn(`Missing 'source' or 'target' in dataset config for ${datasetName}. Skipping.`);
  19. continue;
  20. }
  21. const sourcePath = datasetConfig.source;
  22. const targetPath = datasetConfig.target;
  23. //Check if source file exists
  24. if (!fs.existsSync(sourcePath)) {
  25. console.warn(`Source file not found: ${sourcePath} for dataset ${datasetName}. Skipping.`);
  26. continue;
  27. }
  28. try {
  29. // Copy resources from source to target
  30. await copyResources(sourcePath, targetPath);
  31. console.log(`Synced resources from ${sourcePath} to ${targetPath} for dataset ${datasetName}`);
  32. } catch (error) {
  33. console.error(`Error syncing resources for dataset ${datasetName}:`, error);
  34. }
  35. }
  36. } catch (error) {
  37. console.error("Error reading or parsing config:", error);
  38. }
  39. }
  40. /**
  41. * Copies resources from a source path to a target path.
  42. * @param {string} sourcePath Path to the source directory or file.
  43. * @param {string} targetPath Path to the target directory.
  44. */
  45. async function copyResources(sourcePath, targetPath) {
  46. try {
  47. const sourceFiles = fs.readdirSync(sourcePath);
  48. for (const file of sourceFiles) {
  49. const sourceFilePath = path.join(sourcePath, file);
  50. const targetFilePath = path.join(targetPath, file);
  51. const stat = fs.statSync(sourceFilePath);
  52. if (stat.isFile()) {
  53. fs.copyFileSync(sourceFilePath, targetFilePath);
  54. console.log(`Copied file: ${sourceFilePath} to ${targetFilePath}`);
  55. } else if (stat.isDirectory()) {
  56. fs.mkdirSync(targetFilePath, { recursive: true }); // Create target directory if it doesn't exist
  57. copyResources(sourceFilePath, targetFilePath); // Recursively copy contents
  58. }
  59. }
  60. } catch (error) {
  61. throw error;
  62. }
  63. }
  64. // Example usage (replace with your config file path)
  65. // syncDatasets('config.json');
  66. module.exports = { syncDatasets };

Add your comment