'Get path of exact dependency from node_modules package

How can I get path of exact dependency from a certain node_modules package?

For example:

|- node_modules/
   |- [email protected]/
      |- package.json
   |- package-b/
      |- node_modules/
         |- [email protected]/
      |- package.json
   |- package-c/
      |- package.json

Is there a way I can get the location of package-a that package-b depends on only by reading node_modules/package-b/package.json? In this case, the output should be node_modules/package-b/node_modules/package-a/package.json. While for package-c, it should be node_modules/package-a/package.json.



Solution 1:[1]

You will have to implement the same resolution mechanism as used by Node itself:

  1. Change the current directory to ./node_modules/package-b
  2. If there is a folder node_modules - check whether there is node_modules/package-a subfolder
  3. If there is such a folder - return its full path
  4. If there is no such folder - if the current directory is / (root) then exit otherwise change the current directory to ../ and go to step (2)

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 IVO GELOV