Finding the root directory of a dependency in NPM

Viewed 113

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?

1 Answers

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'
));
Related