function findPkgInfo()

in lib/config/config.js [292:346]


function findPkgInfo() {
  if (pkgInfoCache === undefined) {
    // Determine a good starting dir from which to look for a "package.json".
    let startDir =
      require.main &&
      require.main.filename &&
      path.dirname(require.main.filename);
    if (!startDir && process.argv[1]) {
      // 'require.main' is undefined if the agent is preloaded with `node
      // --require elastic-apm-node/... script.js`.
      startDir = path.dirname(process.argv[1]);
    }
    if (!startDir) {
      startDir = process.cwd();
    }
    pkgInfoCache = {
      startDir,
      path: null,
      data: {},
    };

    // Look up from the starting dir for a "package.json".
    const { root } = path.parse(startDir);
    let dir = startDir;
    while (true) {
      const pj = path.resolve(dir, 'package.json');
      if (fs.existsSync(pj)) {
        pkgInfoCache.path = pj;
        break;
      }
      if (dir === root) {
        break;
      }
      dir = path.dirname(dir);
    }

    // Attempt to load "name" and "version" from the package.json.
    if (pkgInfoCache.path) {
      try {
        const data = JSON.parse(fs.readFileSync(pkgInfoCache.path));
        if (data.name) {
          // For backward compatibility, maintain the trimming done by
          // https://github.com/npm/normalize-package-data#what-normalization-currently-entails
          pkgInfoCache.data.name = data.name.trim();
        }
        if (data.version) {
          pkgInfoCache.data.version = data.version;
        }
      } catch (_err) {
        // Silently leave data empty.
      }
    }
  }
  return pkgInfoCache;
}