1. /**
  2. * Matches file patterns with optional flags.
  3. *
  4. * @param {string} patterns - An array of file patterns (e.g., ['*.js', 'data/*.csv']).
  5. * @param {object} flags - An object containing optional flags (e.g., { recursive: true, exclude: ['node_modules'] }).
  6. * @param {string} directory - The starting directory for the search. Defaults to current directory.
  7. * @returns {Array<string>} - An array of matching file paths.
  8. */
  9. function findFiles(patterns, flags = {}, directory = '.') {
  10. const results = [];
  11. function matchPattern(pattern) {
  12. const glob = require('glob'); // Import glob library
  13. return new Promise((resolve, reject) => {
  14. glob(pattern, {
  15. cwd: directory,
  16. ignore: flags.exclude || [], // Exclude files/directories
  17. strict: false // Allow files that don't match all pattern components
  18. }, (err, files) => {
  19. if (err) {
  20. reject(err);
  21. return;
  22. }
  23. resolve(files);
  24. });
  25. });
  26. }
  27. async function processPatterns() {
  28. for (const pattern of patterns) {
  29. try {
  30. const files = await matchPattern(pattern);
  31. results.push(...files);
  32. } catch (error) {
  33. console.error(`Error matching pattern ${pattern}:`, error);
  34. }
  35. }
  36. }
  37. if (patterns.length === 0) {
  38. return []; // Return empty array if no patterns are provided
  39. }
  40. processPatterns();
  41. return results;
  42. }

Add your comment