Kousha
Kousha

Reputation: 36249

Finding the root directory of a dependency in NPM

Let's say I have installed awesome-package inside my-app, and let's say the structure looks like:

my-app/
  node_modules/
    awesome-package/
      node_modules/
        another-package/
          static/
            index.js
      dist/
        index.js
  dist/
    index.js

Inside my-app/index.js I do require('awesome-package'). Now I want to get the root directory of awesome-package, so I can basically fs.readFileSync something from another-package

How can I get the root directory of a script?

Upvotes: 5

Views: 599

Answers (2)

Anil kumar
Anil kumar

Reputation: 1638

Accepted answer doesn't work on esm package. Accepted answer return cjs path.

Answer for esm path

const fullPath = await import.meta.resolve("package_name");
console.log(fullPath);

need to add flag: --experimental-import-meta-resolve

Upvotes: 0

Josnidhin
Josnidhin

Reputation: 12504

I think require.resolve can be used to achieve that. It will give you the full path to the module. Getting the root directory from that should be easy.

const path = require('path');
let loc = require.resolve('awesome-package');

// most likely something like the following depends on the package
// /path/to/my-app/node_modules/awesome-package/static/index.js
console.log(loc);

// something like the following will give you the root directory
// of the package
console.log(path.join(
  loc.substring(0,a.lastIndexOf('node_modules')),
  'node_modules',
  'awesome-package'
));

Upvotes: 2

Related Questions