Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent require(...) from looking up modules in the parent directory

Tags:

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.

like image 959
thorn0 Avatar asked Sep 08 '15 10:09

thorn0


1 Answers

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

like image 88
hassansin Avatar answered Oct 06 '22 15:10

hassansin