eslint-plugin-unicorn-x
Version:
More than 100 powerful ESLint rules
43 lines (35 loc) • 1.07 kB
JavaScript
import fs from 'node:fs';
import * as find from 'empathic/find';
const directoryCache = new Map();
const dataCache = new Map();
/**
Finds the closest package.json file to the given directory and returns its path and contents.
Caches the result for future lookups.
@param dirname {string}
@return {{ path: string, packageJson: Record<string, unknown> } | undefined}
*/
export function readPackageJson(dirname) {
let packageJsonPath;
if (directoryCache.has(dirname)) {
packageJsonPath = directoryCache.get(dirname);
} else {
packageJsonPath = find.up('package.json', {cwd: dirname});
directoryCache.set(dirname, packageJsonPath);
}
if (!packageJsonPath) {
return;
}
let packageJson;
if (dataCache.has(packageJsonPath)) {
packageJson = dataCache.get(packageJsonPath);
} else {
try {
packageJson = JSON.parse(fs.readFileSync(packageJsonPath));
dataCache.set(packageJsonPath, packageJson);
} catch {
// This can happen if package.json files have comments in them etc.
return;
}
}
return {path: packageJsonPath, packageJson};
}