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.ts56 chars3 lines
Then, create a function that takes a file path as an argument and returns the root directory of that file:
index.ts842 chars27 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.ts138 chars4 lines
gistlibby LogSnag