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.
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
If I correctly understand your question, you should use require.resolve():
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');
require.resolve() is a partial answer. The accepted answer may work for many node modules, but won't work for all of them.
require.resolve("moduleName") doesn't give you the directory where the module is installed; it gives you the location of the file defined in the
main attribute in the module's
That might be
moduleName/index.js or it could be
moduleName/lib/moduleName.js. In the latter case,
path.dirname(require.resolve("moduleName")) will return a directory you may not want or expect:
The correct way to get the complete path to a specific module is by resolving the filename:
let readmePath = require.resolve("moduleName/README.md");
If you just want the directory for the module (maybe you're going to make a lot of
path.join() calls), then resolve the
package.json — which must always be in the root of the project — and pass to
let packagePath = path.dirname(require.resolve("moduleName/package.json"));