module.findPackageJSON(specifier[, base])


稳定性: 1.1 - 处于活跃开发中

  • specifier <string> | <URL> 要检索其 package.json 的模块的指定符。传入 裸指定符 时,将返回包根目录下的 package.json。传入 相对指定符绝对指定符 时,将返回最近的父级 package.json
  • base <string> | <URL> 包含模块的绝对位置(file: URL 字符串或文件系统路径)。对于 CJS,使用 __filename(不要使用 __dirname!);对于 ESM,使用 import.meta.url。如果 specifier 是一个绝对指定符,则无需传递它。
  • 返回值:<string> | <undefined> 如果找到 package.json,则返回一个路径。当 specifier 是一个包时,返回该包的根 package.json;当是相对路径或未解析时,返回离 specifier 最近的 package.json

注意:不要用这个来尝试确定模块格式。有许多因素会影响这个判断;package.json 中的 type 字段是最不具决定性的(例如文件扩展名会覆盖它,而加载器钩子会进一步覆盖)。

注意:目前这仅使用内置的默认解析器;如果注册了 resolve 自定义钩子,它们将不会影响解析。 将来可能会有所改变。

/path/to/project
  ├ packages/
    ├ bar/
      ├ bar.js
      └ package.json // name = '@foo/bar'
    └ qux/
      ├ node_modules/
        └ some-package/
          └ package.json // name = 'some-package'
      ├ qux.js
      └ package.json // name = '@foo/qux'
  ├ main.js
  └ package.json // name = '@foo' 
// /path/to/project/packages/bar/bar.js
import { findPackageJSON } from 'node:module';

findPackageJSON('..', import.meta.url);
// '/path/to/project/package.json'
// Same result when passing an absolute specifier instead:
findPackageJSON(new URL('../', import.meta.url));
findPackageJSON(import.meta.resolve('../'));

findPackageJSON('some-package', import.meta.url);
// '/path/to/project/packages/bar/node_modules/some-package/package.json'
// When passing an absolute specifier, you might get a different result if the
// resolved module is inside a subfolder that has nested `package.json`.
findPackageJSON(import.meta.resolve('some-package'));
// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'

findPackageJSON('@foo/qux', import.meta.url);
// '/path/to/project/packages/qux/package.json'// /path/to/project/packages/bar/bar.js
const { findPackageJSON } = require('node:module');
const { pathToFileURL } = require('node:url');
const path = require('node:path');

findPackageJSON('..', __filename);
// '/path/to/project/package.json'
// Same result when passing an absolute specifier instead:
findPackageJSON(pathToFileURL(path.join(__dirname, '..')));

findPackageJSON('some-package', __filename);
// '/path/to/project/packages/bar/node_modules/some-package/package.json'
// When passing an absolute specifier, you might get a different result if the
// resolved module is inside a subfolder that has nested `package.json`.
findPackageJSON(pathToFileURL(require.resolve('some-package')));
// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'

findPackageJSON('@foo/qux', __filename);
// '/path/to/project/packages/qux/package.json'