new
A Recursive File Search Algorithm in JavaScript
What's it about?
A recursive file search algorithm in JavaScript to find a file in a directory and its subdirectories
2 min to read
algorithm
javascript
nodejs
advanced
Tags
algorithm
javascript
nodejs
advanced
TLDR๐ฅฑ!!!
Just copy the code from here you lazy bum! ๐
Whatโs Going On? ๐ค
So the thing is,
- I wanted a way to search for a file inside a directory and all its subdirectories for this electron app that I was working on.
- Didnโt wanted to use any libraries, because โฆ abandonware ๐.
- Lastly, I only wanted to provide a top-level path to the directory, so that the user doesnโt have to worry about the subdirectories.
So these ๐๐ป three requirements, led me to this ๐๐ป
The Code ๐ป
Now the code might look a bit scary ๐ป, but just go through it line by line and youโll understand I promise. ๐
// substitute with `import` statements if type is `module` const fs = require("fs"); const path = require("path"); function fileSearchRecursive(dirToSearchIn, fileToSearch, callbackFn) { let results = []; fs.readdir(dirToSearchIn, (err, list) => { if (err) return callbackFn(err, []); let pending = list.length; if (!pending) return callbackFn(null, results); list.forEach((file) => { const filename = file; file = path.join(dirToSearchIn, file); fs.stat(file, (_, stat) => { if (stat && stat.isDirectory()) { fileSearchRecursive(file, fileToSearch, (_, res) => { results = results.concat(res); if (!--pending) callbackFn(null, results); }); } else { if (filename.toLowerCase() === fileToSearch.toLowerCase()) { results = results.concat(file); } if (!--pending) callbackFn(null, results); } }); }); }); }
And call it like this:
fileSearchRecursive(__dirname, "rhymbit.exe", (err, res) => { if (err) { console.error(err); } else { console.log(res); } });
Thatโs it!, thanks ๐ค for reading all the way till down here