MCPcopy Index your code
hub / github.com/nodejs/node / findPackageJSON

Function findPackageJSON

lib/internal/modules/package_json_reader.js:311–354  ·  view source on GitHub ↗

* @param {string | URL} specifier The location for which to get the "root" package.json * @param {string | URL} [base] The location of the current module (ex file://tmp/foo.js). * @returns {string}

(specifier, base = 'data:')

Source from the content-addressed store, hash-verified

309 * @returns {string}
310 */
311function findPackageJSON(specifier, base = 'data:') {
312 if (arguments.length === 0) {
313 throw new ERR_MISSING_ARGS('specifier');
314 }
315 try {
316 specifier = `${specifier}`;
317 } catch {
318 validateString(specifier, 'specifier');
319 }
320
321 let parentURL = base;
322 if (!isURL(base)) {
323 validateString(base, 'base');
324 parentURL = path.isAbsolute(base) ? pathToFileURL(base) : new URL(base);
325 }
326
327 if (specifier && specifier[0] !== '.' && specifier[0] !== '/' && !URLCanParse(specifier)) {
328 // If `specifier` is a bare specifier.
329 const { packageJSONPath } = getPackageJSONURL(specifier, parentURL);
330 return packageJSONPath;
331 }
332
333 let resolvedTarget;
334 defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve;
335
336 try {
337 // TODO(@JakobJingleheimer): Detect whether findPackageJSON is being used within a loader
338 // (possibly piggyback on `isForAsyncLoaderHookWorker` from the loader?) and if so:
339 // - When inside, use the default resolve
340 // - (I think it's impossible to use the chain because of re-entry & a deadlock from atomics).
341 // - When outside, use cascadedLoader.resolveSync (not implemented yet, but the pieces exist).
342 resolvedTarget = defaultResolve(specifier, { parentURL: `${parentURL}` }).url;
343 } catch (err) {
344 if (err.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
345 resolvedTarget = err.url;
346 } else {
347 throw err;
348 }
349 }
350
351 const pkg = getNearestParentPackageJSON(fileURLToPath(resolvedTarget));
352
353 return pkg?.path;
354}
355
356module.exports = {
357 read,

Callers 3

index.jsFile · 0.85
index.jsFile · 0.85

Calls 7

getPackageJSONURLFunction · 0.85
fileURLToPathFunction · 0.85
requireFunction · 0.70
isURLFunction · 0.50
pathToFileURLFunction · 0.50
defaultResolveFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…