find the root directory of a file in typescript

To find the root directory of a file in TypeScript, you can use the fs and path modules, both of which are included in Node.js.

First, import these modules at the top of your TypeScript file:

index.ts
import * as fs from "fs";
import * as path from "path";
56 chars
3 lines

Then, create a function that takes a file path as an argument and returns the root directory of that file:

index.ts
function getRootDirectory(filePath: string): string {
  let rootDirectory = "";
  let currentDirectory = filePath;
  
  // Loop until the root directory is found
  while (!rootDirectory) {
    // Get the parent directory of the current directory
    const parentDirectory = path.dirname(currentDirectory);
    
    // Stop the loop if we've reached the root directory
    if (parentDirectory === currentDirectory) {
      rootDirectory = currentDirectory;
    } else {
      // Check if package.json exists in the current directory
      const packageJsonPath = path.join(currentDirectory, "package.json");
      if (fs.existsSync(packageJsonPath)) {
        rootDirectory = currentDirectory;
      } else {
        // Move up to the parent directory
        currentDirectory = parentDirectory;
      }
    }
  }
  
  return rootDirectory;
}
842 chars
27 lines

This function starts at the provided file path and moves up the directory tree until it finds a directory that contains a package.json file (which serves as the root directory of a Node.js project). If it reaches the root directory without finding a package.json file, it simply returns the root directory.

You can then call this function with a file path to get its root directory:

index.ts
const filePath = "/path/to/file.txt";
const rootDirectory = getRootDirectory(filePath);
console.log(rootDirectory); // Output: "/path/to"
138 chars
4 lines

gistlibby LogSnag