Skip to content

Instantly share code, notes, and snippets.

@hyperupcall
Last active May 9, 2020 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyperupcall/8728b708fd731665cfd1ffde6f00f816 to your computer and use it in GitHub Desktop.
Save hyperupcall/8728b708fd731665cfd1ffde6f00f816 to your computer and use it in GitHub Desktop.
/**
* @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