Phrogz
Phrogz

Reputation: 303136

Version number in npm package and module

I am authoring an npm package that has a module and command-line executable. The npm package has a version.

I would like my module to know about this version, so that I can report it from my_executable -v and otherwise use it in the output (e.g. "Generated by MyPackage v1.3.2"). However, I don't want to type the same version number in two places (in my module and my package.json) because at some point I'm guaranteed to mess up and forget to update one or the other. How can I either…


Edit: a simple let pkg = require('./package.json') does not work in my case, because of my project file structure:

mypackage/
  bin/myexecutable    # uses require('../lib/mymodule.js')
  lib/mymodule.js     # needs to load package.json
  package.json

Upvotes: 1

Views: 395

Answers (2)

galkin
galkin

Reputation: 5519

1) The universal solution is:

const path = require('path');
// will be used to check file existence
const {accessSync} = require("fs");

function getMainPackage() {
  let mainModuleName, pathToPackage;

  const mainModuleNameOnError = {
    name: "unknown",
    version: "unknown",
  };

  try {
    mainModuleName = require.main.paths.find((modulesPath) => {
      pathToPackage = path.resolve(modulesPath, "..", "package.json");
      try {
        accessSync(pathToPackage);
      } catch (e) {
        return false;
      }
      return true;
    });
  } catch (e) {
    return mainModuleNameOnError;
  }

  return (mainModuleName)
    ? require(pathToPackage);
    : mainModuleNameOnError;
}

//example
const pkg = getMainPackage();
console.log(pkg.version);

2) If you know where is your package.json placed:

let pkg = require(<the_packagejson_folder> + './package.json');
console.log(pkg.version);

3) If your application is launched with 'npm start', you can simply use:

process.env.npm_package_version

See package.json vars for more details.

Upvotes: 1

Peter Reid
Peter Reid

Reputation: 5397

You can extract the version of your package from package.json as follows:

let pkg = require('./package.json');

Access pkg.version to get the version e.g.:

console.log(pkg.version);

If package.json is not in the same directory as the file you are executing:

let pkg = require(__dirname + '/path/to/package.json')

Upvotes: 2

Related Questions