src: add cache to nearest parent package json

PR-URL: https://github.com/nodejs/node/pull/59086
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Jacob Smith <jacob@frende.me>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
This commit is contained in:
Ilyas Shabi 2025-07-21 17:26:02 +02:00 committed by GitHub
parent 24065f066f
commit 2a7fb0a680
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -5,6 +5,7 @@ const {
JSONParse,
ObjectDefineProperty,
RegExpPrototypeExec,
SafeMap,
StringPrototypeIndexOf,
StringPrototypeSlice,
} = primordials;
@ -28,6 +29,8 @@ const path = require('path');
const { validateString } = require('internal/validators');
const internalFsBinding = internalBinding('fs');
const nearestParentPackageJSONCache = new SafeMap();
/**
* @typedef {import('typings/internalBinding/modules').DeserializedPackageConfig} DeserializedPackageConfig
* @typedef {import('typings/internalBinding/modules').PackageConfig} PackageConfig
@ -131,13 +134,21 @@ function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
* @returns {undefined | DeserializedPackageConfig}
*/
function getNearestParentPackageJSON(checkPath) {
if (nearestParentPackageJSONCache.has(checkPath)) {
return nearestParentPackageJSONCache.get(checkPath);
}
const result = modulesBinding.getNearestParentPackageJSON(checkPath);
if (result === undefined) {
nearestParentPackageJSONCache.set(checkPath, undefined);
return undefined;
}
return deserializePackageJSON(checkPath, result);
const packageConfig = deserializePackageJSON(checkPath, result);
nearestParentPackageJSONCache.set(checkPath, packageConfig);
return packageConfig;
}
/**