const fs = require('fs');
const path = require('path');
/**
* Reads data from a text file and returns it as a string.
* @param {string} filePath The path to the text file.
* @returns {Promise<string>} A promise that resolves with the file content, or rejects with an error.
*/
async function readTextFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
/**
* Reads data from multiple text files and concatenates them.
* @param {string[]} filePaths An array of paths to the text files.
* @returns {Promise<string>} A promise that resolves with the concatenated content, or rejects with an error.
*/
async function readTextFiles(filePaths) {
try {
const fileContents = [];
for (const filePath of filePaths) {
const content = await readTextFile(filePath);
fileContents.push(content);
}
return fileContents.join('\n'); //Join with newline for readability
} catch (error) {
console.error("Error reading files:", error);
throw error; //Re-throw to handle errors upstream
}
}
//Example Usage:
async function main() {
const filePaths = ['data1.txt', 'data2.txt', 'data3.txt']; // Replace with your file paths
try {
const combinedData = await readTextFiles(filePaths);
console.log(combinedData);
} catch (error) {
console.error("Failed to read files:", error);
}
}
//Call the main function
main();
Add your comment