1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Reads data from a text file and returns it as a string.
  5. * @param {string} filePath The path to the text file.
  6. * @returns {Promise<string>} A promise that resolves with the file content, or rejects with an error.
  7. */
  8. async function readTextFile(filePath) {
  9. return new Promise((resolve, reject) => {
  10. fs.readFile(filePath, 'utf8', (err, data) => {
  11. if (err) {
  12. reject(err);
  13. return;
  14. }
  15. resolve(data);
  16. });
  17. });
  18. }
  19. /**
  20. * Reads data from multiple text files and concatenates them.
  21. * @param {string[]} filePaths An array of paths to the text files.
  22. * @returns {Promise<string>} A promise that resolves with the concatenated content, or rejects with an error.
  23. */
  24. async function readTextFiles(filePaths) {
  25. try {
  26. const fileContents = [];
  27. for (const filePath of filePaths) {
  28. const content = await readTextFile(filePath);
  29. fileContents.push(content);
  30. }
  31. return fileContents.join('\n'); //Join with newline for readability
  32. } catch (error) {
  33. console.error("Error reading files:", error);
  34. throw error; //Re-throw to handle errors upstream
  35. }
  36. }
  37. //Example Usage:
  38. async function main() {
  39. const filePaths = ['data1.txt', 'data2.txt', 'data3.txt']; // Replace with your file paths
  40. try {
  41. const combinedData = await readTextFiles(filePaths);
  42. console.log(combinedData);
  43. } catch (error) {
  44. console.error("Failed to read files:", error);
  45. }
  46. }
  47. //Call the main function
  48. main();

Add your comment