const fs = require('fs').promises;
const path = require('path');
/**
* Aggregates values from multiple files with a timeout.
* @param {string[]} filePaths Array of file paths.
* @param {number} timeout Timeout in milliseconds.
* @returns {Promise<object>} A promise that resolves to an object containing the aggregated values, or rejects with an error.
*/
async function aggregateFiles(filePaths, timeout) {
const startTime = Date.now();
const results = {};
const promises = [];
for (const filePath of filePaths) {
promises.push(
fs.readFile(filePath, 'utf8')
.then(content => {
try {
// Parse the file content and extract values. Adapt this part based on your file format.
const parsedData = parseFileContent(content);
return parsedData;
} catch (error) {
console.error(`Error parsing file ${filePath}:`, error);
return null; // or handle the error differently
}
})
.catch(error => {
console.error(`Error reading file ${filePath}:`, error);
return null; // or handle the error differently
})
.finally(() => {
// Remove the promise from the list
promises.splice(promises.indexOf(this), 1);
})
);
}
try {
const aggregatedResults = await Promise.all(promises);
for (const result of aggregatedResults) {
if(result) {
for (const key in result) {
if (result.hasOwnProperty(key)) {
if (!results[key]) {
results[key] = result[key];
} else {
results[key] += result[key]; // or perform other aggregation logic
}
}
}
}
}
return results;
} catch (error) {
console.error("AggregateFiles timed out:", error);
return { error: "Timeout" };
}
}
/**
* Placeholder function to parse file content. Replace with your actual parsing logic.
* @param {string} content The content of the file.
* @returns {object} The parsed data.
*/
function parseFileContent(content) {
//Example: Assuming each line contains "key=value"
const lines = content.split('\n');
const data = {};
for(const line of lines) {
const [key, value] = line.split('=');
data[key.trim()] = value.trim();
}
return data;
}
module.exports = aggregateFiles;
Add your comment