Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I immediately break from searching through directory recursively once desired file is found?

I'm recursively searching through a directory structure for a file with a specific name. I want to break as soon as the first instance of that file is found. How can I accomplish this? Currently it's continuing to parse through the rest of the files even after it's found an instance of the file i'm looking for.

async function walkDir(dir: string, callback: Function) {
  for (const f of await fs.readdir(dir)) {
    const dirPath = path.join(dir, f);
    if ((await fs.stat(dirPath)).isDirectory())
      walkDir(dirPath, callback);
    else if (callback(path.join(dir, f)))
      return;
  }

let foundFile = false;
await walkDir(startDir, function (f: string) {
  console.log(f);
  if (path.basename(f) === 'manifest.xml') {
    foundFile = true;
    return;
  }
});
like image 638
John Bergqvist Avatar asked Jan 20 '26 02:01

John Bergqvist


1 Answers

Simplest option is probably to return true/false from the callback and from walkDir if the value was found.

async function walkDir(dir: string, callback: (path: string) => boolean): Promise<boolean> {
    for (const f of await fs.readdir(dir)) {
        const dirPath = path.join(dir, f);
        if ((await fs.stat(dirPath)).isDirectory()) {
            if (await walkDir(dirPath, callback)) {
                return true
            }
        }
        else if (callback(path.join(dir, f))) {
            return true;
        }
    }
    return false;
}


var args= { dir: "" };
(async function () {
    let foundFile = false;
    await walkDir(args.dir, function (f: string) {
        console.log(f);
        if (path.basename(f) === 'manifest.xml') {
            foundFile = true;
            return true;
        }
        return false;
    });
})();

Play

This can also simplify the call for the use-case you have in your sample code:

let foundFile = await walkDir(args.dir, f => path.basename(f) === 'manifest.xml');
like image 138
Titian Cernicova-Dragomir Avatar answered Jan 22 '26 18:01

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!