1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Matches patterns in text files.
  5. * @param {string[]} filePaths - Array of file paths to search.
  6. * @param {string} pattern - The pattern to search for.
  7. * @param {function} callback - Callback function to handle results.
  8. */
  9. function matchPatterns(filePaths, pattern, callback) {
  10. if (!Array.isArray(filePaths) || filePaths.length === 0) {
  11. callback(new Error("File paths must be a non-empty array."));
  12. return;
  13. }
  14. if (typeof pattern !== 'string' || pattern.length === 0) {
  15. callback(new Error("Pattern must be a non-empty string."));
  16. return;
  17. }
  18. if (typeof callback !== 'function') {
  19. callback(new Error("Callback must be a function."));
  20. return;
  21. }
  22. let results = [];
  23. function processFile(filePath) {
  24. fs.readFile(filePath, 'utf8', (err, data) => {
  25. if (err) {
  26. console.error(`Error reading file ${filePath}: ${err}`);
  27. callback(err);
  28. return;
  29. }
  30. const matches = findMatches(data, pattern);
  31. if (matches.length > 0) {
  32. results.push({ filePath: filePath, matches: matches });
  33. }
  34. if (results.length === filePaths.length) {
  35. callback(null, results);
  36. }
  37. });
  38. }
  39. function findMatches(text, pattern) {
  40. const regex = new RegExp(pattern, 'g'); // 'g' for global search
  41. const matches = [];
  42. let match;
  43. while ((match = regex.exec(text)) !== null) {
  44. matches.push(match[0]); // Store the matched text
  45. }
  46. return matches;
  47. }
  48. filePaths.forEach(filePath => {
  49. processFile(filePath);
  50. });
  51. }
  52. module.exports = matchPatterns;

Add your comment