leodutra
7/4/2016 - 6:33 PM

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.

/**
 * 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;
}