2 minute read

This is a quick guide to show a trick on how to recursively scan all parent folders using nodejs, fs and path.

Lets say you want to find a config file for the current context, for instance a code-file or similar. Lets say you are looking for the closest .gitignore file to a given file. You have the path of the currently open file, but need to find a file in any parent directory.

In nodejs this is easy when you know the trick!

The trick is to use path.dirname() on a directory to get the parent directory. Note: This only works until you are at root, so you need to exit when the same path is retried.

A simple example implementation is given below.

import fs from "fs";
import path from "path";

function findFileInParentDirectoryRecursive(currentFileFullPath: string, fileToFind: string): string | null {
    let parentDirectory = path.dirname(currentFileFullPath);
    while (fs.existsSync(parentDirectory)) {
      const fileToFindPath = path.join(parentDirectory, fileToFind);
      if (fs.existsSync(fileToFindPath)) {
        return fileToFindPath;
      }

      // The trick is here:
      // Using path.dirname() of a directory returns the parent directory!
      const parentDirname = path.dirname(parentDirectory);
      // But only to a certain point (file system root) (So to avoid infinite loops lets stop here)
      if (parentDirectory === parentDirname) {
        return null;
      }

      parentDirectory = parentDirname;
    }

    return null;
}

The end

Ok, so this was a quick one. But I did not find anything on how to recursively scan a parent folder in nodejs on the internet, so why not document it here.

That’s it for this time!

// Nils Henrik

Tags:

Categories:

Updated: