In node.JS how can I get the path of a module I have loaded via require that is *not* mine (i.e. in some node_module)

前端 未结 7 1760
清歌不尽
清歌不尽 2020-12-02 15:16

I require a module that was installed via npm. I want to access a .js file subordinate to that module (so I can subclass a Constructor method in it). I can\'t (well, don\'t

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 15:48

    Jason's answer was the best answer, until Node.js ESM and the exports field came out.

    Now that Node supports packages with an exports field that by default will prevent files like package.json from being resolvable unless the package author explicitly decides to expose them, the trick in Jason's answer will fail for packages that do not explicitly expose package.json.

    There is a package called resolve-package-path that does the trick.

    Here's how to use it:

    const resolvePkg = require('resolve-package-path')
    
    console.log(resolvePkg('@some/package'))
    

    which will output something like

    /path/to/@some/package/package.json
    

    regardless of what the package's exports field contains.

提交回复
热议问题