Files
Language-Notes-Organizer/src/fileReader.js
2025-09-05 14:38:22 -05:00

44 lines
1.4 KiB
JavaScript

// Module for reading and filtering files
const fs = require('fs');
const path = require('path');
/**
* Recursively scans a directory, filters files by a pattern, and reads their content.
* @param {string} dirPath - The path to the directory.
* @param {string} pattern - The keyword pattern to match in the file name.
* @returns {{filePath: string, content: string}[]} - An array of objects, each with the file path and its content.
*/
function getFileContents(dirPath, pattern) {
let fileData = [];
function scan(directory) {
try {
const entries = fs.readdirSync(directory, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
scan(fullPath);
} else {
const regex = new RegExp(pattern, 'i');
if (!pattern || regex.test(entry.name)) {
try {
const content = fs.readFileSync(fullPath, 'utf8');
fileData.push({ filePath: fullPath, content });
} catch (readError) {
console.error(`Error reading file ${fullPath}:`, readError);
}
}
}
}
} catch (scanError) {
console.error(`Error scanning directory ${directory}:`, scanError);
}
}
scan(dirPath);
return fileData;
}
module.exports = { getFileContents };