'Get installed package root path from within package

I am building an npm package which is basically an CLI tool. It is intended to be installed globally and used as CLI with dist/clj.js, but can also be installed as a regular dependency and accessed via dist/index.js.

From inside .js files of my package (like dist/cli.js or dist/index.js) I want to get an absolute path to the root of my package (where package.json is located).

I know this can be done with __dirname but for different files in my project it require different actions:

// dist/cli.js
console.log(require('path').join(__dirname, '..'));

// dist/a/b/c/foo.js
console.log(require('path').join(__dirname, '..', '..', '..', '..'));

Is there a better way to get the root of both globally or locally installed package from any .js file inside this package regardless of the folder this package is used in?



Solution 1:[1]

This code seems to work from any file within package:

const path = require('path');

let packageRootPath = path.join(path.dirname(require.main.filename), '..');

.. in the end needed to jump from src/dist to the root since all my js files are located in src/dist forders.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CMTV