/**
* Matches file patterns with optional flags.
*
* @param {string} patterns - An array of file patterns (e.g., ['*.js', 'data/*.csv']).
* @param {object} flags - An object containing optional flags (e.g., { recursive: true, exclude: ['node_modules'] }).
* @param {string} directory - The starting directory for the search. Defaults to current directory.
* @returns {Array<string>} - An array of matching file paths.
*/
function findFiles(patterns, flags = {}, directory = '.') {
const results = [];
function matchPattern(pattern) {
const glob = require('glob'); // Import glob library
return new Promise((resolve, reject) => {
glob(pattern, {
cwd: directory,
ignore: flags.exclude || [], // Exclude files/directories
strict: false // Allow files that don't match all pattern components
}, (err, files) => {
if (err) {
reject(err);
return;
}
resolve(files);
});
});
}
async function processPatterns() {
for (const pattern of patterns) {
try {
const files = await matchPattern(pattern);
results.push(...files);
} catch (error) {
console.error(`Error matching pattern ${pattern}:`, error);
}
}
}
if (patterns.length === 0) {
return []; // Return empty array if no patterns are provided
}
processPatterns();
return results;
}
Add your comment