1

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.

3
  • 1
    Try require('path').dirname(module.main.filename) Commented Oct 30, 2019 at 13:44
  • module.main is undefined Commented Oct 30, 2019 at 13:48
  • 2
    A typo. I mean require.main Commented Oct 30, 2019 at 13:51

1 Answer 1

1

The __dirname of main module can be found as follow:

require('path').dirname(require.main.filename); 

Since Yury Tarabanko posted a comment and not an answer, I post his response here so I can mark the question as resolved.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.