Skip to content

Instantly share code, notes, and snippets.

@leodutra
Created July 4, 2016 18:33
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 leodutra/d11a9618a2d26b83372a9659cb881534 to your computer and use it in GitHub Desktop.
Save leodutra/d11a9618a2d26b83372a9659cb881534 to your computer and use it in GitHub Desktop.
Find the closest package.json file, starting at process.cwd (by default) and working up to root.
/**
* Find the closest package.json file, starting at process.cwd (by default),
* and working up to root.
*
* @param {string} [startDir=process.cwd()] Starting directory
* @returns {string} Absolute path to closest package.json file
*/
function findPackageJson(startDir) {
var dir = path.resolve(startDir || process.cwd());
do {
var pkgfile = path.join(dir, "package.json");
if (!fs.existsSync(pkgfile)) {
dir = path.join(dir, "..");
continue;
}
return pkgfile;
} while (dir !== path.resolve(dir, ".."));
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment