node.jsnpmnpm-scripts

how to get the path of an installed npm package via npm CLI/API?


i'm writing an npm script, which is packed as an npm package, exposing the main executable to node_modules/.bin to its hosting project.

this script has its own npm dependencies, and as the script flow relies on copying one of these dependencies to a different location, it needs to know where was that dependency installed.

how can i find (via API or the npm CLI) where was that dependency installed inside the host's node_modules?


Solution

  • see a more elaborated answer here. this answer is kept for reference.


    you can use npm ls with the --parseable flag, which will:

    Show parseable output instead of tree view.

    for example:

    $ npm ls my-dep -p
    /Users/my-user/dev/host-project/node_modules/my-dep
    

    be aware that the output may contain some irrelevant errors as well (e.g. about extraneous installations) — to work around this, activate the --silent flag (see loglevel in the docs):

    $ npm ls my-dep -ps
    

    you can integrate this command into your script using a child process, in which case it's preferred to run the command without the --silent flag to allow capturing any error.

    if an error is caught, you can then decide whether it's fatal or not (e.g. the aforementioned error about extraneous package should be ignored).