Last active
May 9, 2020 11:16
-
-
Save hyperupcall/8728b708fd731665cfd1ffde6f00f816 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @description given the location of this file, find the package.json of the closest parent package | |
* @async | |
* @return {string} absolute path of parent packageJson file | |
*/ | |
export function findParentPackageJson() { | |
function parentDirOf(fileOrDir: string): string { | |
return path.join(fileOrDir, '..') | |
} | |
async function packageJsonExists(dir: string): Promise<boolean> { | |
const dirents = await fs.promises.readdir(dir, { withFileTypes: true }) | |
return dirents.some(dirent => dirent.isFile() && dirent.name === 'package.json') | |
} | |
// currentLocation could be a file or dir | |
async function walkUp(currentLocation: string): Promise<string> { | |
if (await packageJsonExists(currentLocation)) { | |
return path.join(currentLocation, 'package.json') | |
} | |
else { | |
const newLocation = parentDirOf(currentLocation) | |
return walkUp(newLocation) | |
} | |
} | |
// const currentFile = fileURLToPath(import.meta.url) | |
const currentFile = __filename; | |
const currentDir = parentDirOf(currentFile) | |
return walkUp(currentDir) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment