The root directory of my Node project is in a directory that itself is a root of another Node project. So both folders contain package.json
and node_modules
. The problem is that in the inner project, sometimes I require
modules not installed in this project. But Node just silently finds them in the parent project's node_modules
which leads to annoying surprises. Can I somehow prevent it from doing so? I'd like not to change the directory structure of the projects unless it's the only solution.
Node tries to resolve current module path name and concatenates node_modules
to each of it's parent directory. [Source].
You can override this method at the top of your project module and add some logic to exclude the parent directories from the result path array.
//app.js <-- parent project module, should be added at the top var Module = require('module').Module; var nodeModulePaths= Module._nodeModulePaths; //backup the original method Module._nodeModulePaths = function(from) { var paths = nodeModulePaths.call(this, from); // call the original method //add your logic here to exclude parent dirs, I did a simple match with current dir paths = paths.filter(function(path){ return path.match(__dirname) }) return paths; };
inspired by this module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With