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 1763
清歌不尽
清歌不尽 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:45

    According to @anatoliy solution, On MacOS X I have found the lookup paths doing

    require('module')._resolveLookupPaths('myModule')
    

    so I get the resolved lookup paths

    [ 'myModule',
      [ '/Users/admin/.node_modules',
        '/Users/admin/.node_libraries',
        '/usr/local/lib/node' ] ]
    

    whereas the

    require('module')._resolveFilename('myModule')
    

    will not resolve the module I was looking for anyways, in fact the crazy thing is that the _load will not resolve the module:

    > require('module')._load('myModule')
    Error: Cannot find module 'myModule'
        at Function.Module._resolveFilename (module.js:440:15)
        at Function.Module._load (module.js:388:25)
        at repl:1:19
        at sigintHandlersWrap (vm.js:32:31)
        at sigintHandlersWrap (vm.js:96:12)
        at ContextifyScript.Script.runInContext (vm.js:31:12)
        at REPLServer.defaultEval (repl.js:308:29)
        at bound (domain.js:280:14)
        at REPLServer.runBound [as eval] (domain.js:293:12)
        at REPLServer. (repl.js:489:10)
    

    while the require will:

    > require('myModule')
    

    but I don't have this module in

    myProject/node_modules/
    myProject/node_modules/@scope/
    /usr/local/lib/node_modules/
    /usr/local/lib/node_modules/@scope
    /usr/local/lib/node_modules/npm/node_modules/
    /usr/local/lib/node_modules/npm/node_modules/@scope
    $HOME/.npm/
    $HOME/.npm/@scope/
    

    so where is this module???

    First I had to do a $ sudo /usr/libexec/locate.updatedb Then after some coffee I did locate myModule or better locate myModule/someFile.js

    et voilà, it comes out that it was in a parent folder of my project i.e. outside my project root folder:

    $pwd
    /Users/admin/Projects/Node/myProject
    $ ls ../../node_modules/myModule/
    

    so you cannot avoid to rm -rf ../../node_modules/myModule/ and a fresh npm install.

    I can argue that no one instructed npm to scan my computer in search for modules elsewhere than my project root folder where it was supposed to run or in the default modules search path.

提交回复
热议问题