Prevent the requirement (...) from searching for modules in the parent directory

The root directory of my Node project is in a directory that itself is the root of another Node project. Thus, both folders contain package.json and node_modules . The problem is that in the internal project sometimes I require modules are not installed in this project. But Node just silently finds them in the parent project node_modules , which leads to annoying surprises. Can I somehow prevent this? I would not want to change the directory structure of projects if this is not the only solution.

+6
source share
1 answer

Node tries to resolve the current module path name and merges node_modules into each of its parent directories. [Source] .

You can override this method at the top of the project module and add some logic to exclude parent directories from the array of result paths.

 //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

+6
source

All Articles