All files / utils package-utils.ts

100% Statements 30/30
100% Branches 4/4
100% Functions 1/1
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 3x  
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
 
/**
 * Looks up the installed package version in the node_modules directory.
 *
 * @param dir The project directory.
 * @param packageName The name of the package to lookup.
 * @returns The version of the package or null if the package is not installed.
 */
export const getActualPackageVersion = async (
  dir: string,
  packageName: string,
) => {
  const packageJsonPath = `${dir}/node_modules/${packageName}/package.json`;
 
  if (!existsSync(packageJsonPath)) {
    return null;
  }
 
  try {
    const packageJson = await readFile(packageJsonPath, { encoding: "utf-8" });
    const packageJsonContents = JSON.parse(packageJson);
    const version = packageJsonContents.version;
 
    return version;
  } catch (e) {
    return null;
  }
};