A Recursive File Search Algorithm in JavaScript

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, "techy-rabbit.exe", (err, res) => { if (err) { console.error(err); } else { console.log(res); } });

That’s it!, thanks 🤗 for reading all the way till down here