v1.0
This commit is contained in:
43
src/fileReader.js
Normal file
43
src/fileReader.js
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
// 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 };
|
||||
Reference in New Issue
Block a user