在node.JS中,我如何获得通过require不是*我的(即在某些node_module中)加载的模块的路径 [英] 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)
问题描述
我需要一个通过npm安装的模块.我想访问从属于该模块的.js文件(因此我可以在其中继承一个Constructor方法).我不能(当然,不想)修改模块的代码,所以没有地方提取其__dirname.
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 want to) modify the module's code, so don't have a place to extract its __dirname.
我知道以下问题,但这是关于获得代码控制模块的路径的(因此,__dirname是解决方案): 在Node.js中我该如何分辨此模块的路径?
I am aware of the following question, but it is about getting the path of a module that one has code control over (hence, __dirname is the solution): In Node.js how can I tell the path of `this` module?
~~~
更好的办法是获取模块的已加载模块信息
Even better would be to get the module's loaded module info
推荐答案
如果我正确理解了您的问题,则应使用 require.resolve():
If I correctly understand your question, you should use require.resolve():
使用内部的require()机制查找模块的位置,而不是加载模块,只需返回已解析的文件名即可.
Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.
示例:var pathToModule = require.resolve('module');
这篇关于在node.JS中,我如何获得通过require不是*我的(即在某些node_module中)加载的模块的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!