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

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