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)


Question

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

1
77
5/23/2017 12:18:13 PM

Accepted Answer

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.

Example: var pathToModule = require.resolve('module');

111
3/23/2018 1:25:27 PM

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 package.json.

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: node_modules/moduleName/lib

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 path.dirname():

let packagePath = path.dirname(require.resolve("moduleName/package.json"));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon