1. const fs = require('fs').promises;
  2. const path = require('path');
  3. /**
  4. * Aggregates values from multiple files with a timeout.
  5. * @param {string[]} filePaths Array of file paths.
  6. * @param {number} timeout Timeout in milliseconds.
  7. * @returns {Promise<object>} A promise that resolves to an object containing the aggregated values, or rejects with an error.
  8. */
  9. async function aggregateFiles(filePaths, timeout) {
  10. const startTime = Date.now();
  11. const results = {};
  12. const promises = [];
  13. for (const filePath of filePaths) {
  14. promises.push(
  15. fs.readFile(filePath, 'utf8')
  16. .then(content => {
  17. try {
  18. // Parse the file content and extract values. Adapt this part based on your file format.
  19. const parsedData = parseFileContent(content);
  20. return parsedData;
  21. } catch (error) {
  22. console.error(`Error parsing file ${filePath}:`, error);
  23. return null; // or handle the error differently
  24. }
  25. })
  26. .catch(error => {
  27. console.error(`Error reading file ${filePath}:`, error);
  28. return null; // or handle the error differently
  29. })
  30. .finally(() => {
  31. // Remove the promise from the list
  32. promises.splice(promises.indexOf(this), 1);
  33. })
  34. );
  35. }
  36. try {
  37. const aggregatedResults = await Promise.all(promises);
  38. for (const result of aggregatedResults) {
  39. if(result) {
  40. for (const key in result) {
  41. if (result.hasOwnProperty(key)) {
  42. if (!results[key]) {
  43. results[key] = result[key];
  44. } else {
  45. results[key] += result[key]; // or perform other aggregation logic
  46. }
  47. }
  48. }
  49. }
  50. }
  51. return results;
  52. } catch (error) {
  53. console.error("AggregateFiles timed out:", error);
  54. return { error: "Timeout" };
  55. }
  56. }
  57. /**
  58. * Placeholder function to parse file content. Replace with your actual parsing logic.
  59. * @param {string} content The content of the file.
  60. * @returns {object} The parsed data.
  61. */
  62. function parseFileContent(content) {
  63. //Example: Assuming each line contains "key=value"
  64. const lines = content.split('\n');
  65. const data = {};
  66. for(const line of lines) {
  67. const [key, value] = line.split('=');
  68. data[key.trim()] = value.trim();
  69. }
  70. return data;
  71. }
  72. module.exports = aggregateFiles;

Add your comment