I currently have a findFile function I use within a forEach Loop to iterate through an array of filenames and then provide a new array of the file system paths for each of the filenames within the original array:
var dir = 'Some File System Path';
const fs = require('fs');
const findFile = function (dir, pattern) {
var results = [];
fs.readdirSync(dir).forEach(function (dirInner) {
dirInner = path.resolve(dir, dirInner);
var stat = fs.statSync(dirInner);
if (stat.isDirectory()) {
results = results.concat(findFile(dirInner, pattern));
}
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
return results;
};
var newFileArr = ['1.txt', 'file2.txt', 'file3.txt', 'file4.txt']
function fpArr(newFileArr) {
const fpArray = [];
newFileArr.forEach((file => {
fpArray.push(findFile(dir, file).toString())
//console.log(fpArray)
}));
OutPut:
[
/some/file/path/file1.txt,
/some/file/path/1.txt,
/some/file/path/file2.txt,
/some/file/path/file3.txt,
/some/file/path/file4.txt
]
The issue I am facing is my findFile looks for a pattern match and it picks up the path for "1.txt" presumably when it is searching for "file1.txt". I know this is an edge case, but it is an important edge case because other filenames may end with the same letters or numbers and I do not want those to be picked up in the file path array output. I have tried several ideas such as ".match()" and ".startsWith" however those will only work with a string literal or regEx as far as I can tell which causes the search itself to fail. I am looking to see if there is a way to get the findFile function to do an exact match based off a variable of some string value? Any help getting me in the right direction is appreciated.
[
'K_01.00.0000.iar',
'HELLOWORLDKLA_01.00.0000.iar',
'HELLO_KLA_01.00.0000.iar',
'KLA_01.22.7895.iar',
'KLA_HELLO_WORLD_2_01.00.0000.iar',
'KLA_02_WORLD_01.00.0000.iar'
]
[]
Above are the actual 2 arrays I am working with. The first array is just a simply array of filenames. The bottom array has been run through both sync and you async/await solution. For some reason even with the RegExp added it still picks up 2 files which are not listed in the filename array. I added the file paths to show none of the files are in the root directory and I spread out the files into sub directories to ensure the recursive search is working. I will keep messing with it to see if I can figure out why the RegExp solution is bringing these files into the array when they shouldn't be....