I'm writting a NPM package and I need to know, within this package, what is the __dirname value of the main module.
By "main module", I mean the module that isn't a dependency.
example:
a-project ├─ index.js <--- main module ├─ node_modules │ ├─ my-package <--- can be a symlink ┊ ┊ └─ index.js <--- I'm here I tried 2 things:
try 1 (using the current __dirname):
const path = require('path'); console.log(`${__dirname}${path.sep}..${path.sep}..`); const path = require('path'); console.log(path.resolve(__dirname, '..', '..')); -> doesn't work if the package isn't in node_modules but symlinked in node_modules (some packages manager like pnpm do this)
try 2 (using process.argv[1]):
const escapeStringRegexp = require('escape-string-regexp'); const path = require('path'); const escapedPathSep = escapeStringRegexp(path.sep); console.log(process.argv[1].match(new RegExp(`^(.*)${escapedPathSep}.*$`))[1]); const path = require('path'); console.log(path.dirname(process.argv[1])); -> doesn't work in production when the main module is lauched by pm2 because process.argv[1] become the location of pm2
I though to use callsite but I think that it will not work if the package isn't a direct dependency of the main module.
require('path').dirname(module.main.filename)module.mainis undefinedrequire.main