0

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....

1 Answer 1

1

I'm afraid I don't have enough reputation to comment so am posting an answer!

Your code seems to work and if I understand rightly that you want to find all files from a list against a directory and sub directories giving you the paths to these files. Is that correct?

When I ran your code it does indeed pick up the four files in newFileArr and excludes the 1.txt, I've created a codesandbox demo to show you with dummy files.

I've also taken the liberty to create a codesandbox that demonstrates how to do this in a single function using RegExp and map to create dynamic regex expressions if that is useful.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, I am generating a dynamic list of filenames, then using Nodejs to look within the file system to provide paths to the filenames. Array of filepaths is being used when making an API call to our cloud provider where I upload the files. Let me check out your RegExp example.....I thank you for posting....I'll provide another update once I have had some time to look through more thoroughly! Thanks!
I updated the example, to accurately reflect the situation. It wasn't until I tried out your code solution and it provided the same result it occurred to me I had a typo. I updated the newFileArr = ['1.txt', 'file2.txt', 'file3.txt', 'file4.txt']. When searching based on the updated array you get the output as shown which includes "file1.txt". This (I think) is due to the search not doing an Exact string match rather doing a pattern match and hitting on the last character, i.e. '1.txt'.
I am going to see if your other solution has a way to do a RegExp for an exact match based off of "filters".....
I see that explains why you have an issue with endsWith as it will match both files but yes the regex version I did should fix that. I'm using async/await in my demo but you can achieve the same with sync fs methods
I've changes the rehgex tro be new RegExp(/${filters.join("|")}$); which will match anything after the / character that ends with your filenames. This won't work if you are looking for files in your root directory though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.