0

I am attempting to do a file search based off array of file names and root directory. I found some file search snips online that seem to work when I am finding just 1 single file, but it will not work when there is more than 1 file specified. Below is the snippet:

const fs = require('fs');

const path = require('path');
var dir = '<SOME ROOT DIRECTORY>';
var file = 'Hello_World.txt'
var fileArr = ['Hello_World.txt', 'Hello_World2.txt', 'Hello_World3.txt'];

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;
};

console.log(findFile(dir, file));

Any thoughts on how I can get this working with an array rather than just a single file string?

Doing the following seems to be working, but didn't know if there were other ways to do this which may be simpler:

newFileArr = [];

fileArr.forEach((file => {
    //findFile(dir, file).toString();
    console.log(findFile(dir, file).toString());
}));

2
  • patterns.indexOf(dirInner) ?? or patterns.some(pattern => dirInner.endsWith(pattern)) Commented Mar 30, 2020 at 16:59
  • you are doing correct! Commented Mar 30, 2020 at 17:00

1 Answer 1

1

The only thing that needs to change is the condition to determine if an individual filepath meets the search criteria. In the code you've posted, it looks like dirInner.endsWith(pattern), which says "does the filepath end with the given pattern?"

We want to change that to say "does the filepath end with any of the given patterns?" And closer to how the code will look, we can rephrase that as "Can we find a given pattern such that the filepath ends with that pattern?"

Let's rename pattern to patterns. Then we can simple replace dirInner.endsWith(patterns) with patterns.some(pattern => dirInner.endsWith(pattern))

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

1 Comment

Excellent, let me work with this for a few...Thanks!

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.