简体   繁体   中英

Nodejs File Search from Array of Filenames

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM