UNPKG

@jsbits/get-package-version

Version:

Get the version of the package.json file found in the given directory or in one of its parents.

50 lines 1.75 kB
"use strict"; var path = require("path"); var fs = require("fs"); /** * Returns the version on package.json file, if it exists. * * @param {string} pkgPath Path to check out. * @returns {string|undefined} Version * @private */ var extractVersion = function (pkgPath) { var pkgname = path.join(pkgPath, 'package.json'); var version; // Try to get the version if package.json exists. if (fs.existsSync(pkgname)) { try { version = require(pkgname).version; } catch ( /**/_a) { /**/ } } return version; }; /** * Returns the version of the first package.json file found in the given * directory or in one of its parents. * * - If you don't provide a path, the search starts in the current one. * - The provided path can be relative to the current working directory. * - Packages with a missing or empty `version` property are ignored. * * @param {string} [pkgPath=.] Initial directory to search, defaults to `process.cwd()`. * @returns {string} The package version, or an empty string if it could not be found. * @since 1.0.0 */ var getPackageVersion = function _getPackageVersion(pkgPath) { // Start with the current working directory, with normalized slashes pkgPath = (pkgPath ? path.resolve(pkgPath) : process.cwd()).replace(/\\/g, '/'); while (~pkgPath.indexOf('/')) { // Try to get the version, the package may not contain one. var version = extractVersion(pkgPath); if (version) { return version; } // package.json not found or does not contains version, move up pkgPath = pkgPath.replace(/\/[^/]*$/, ''); } return ''; }; module.exports = getPackageVersion; //# sourceMappingURL=index.js.map