防止要求(…)查找父目录中的模块

我的Node项目的根目录位于一个本身是另一个Node项目的根目录中。 所以这两个文件夹都包含package.jsonnode_modules 。 问题是在内部项目中,有时候我require在这个项目中没有安装的模块。 但是Node只是默默地在父项目的node_modulesfind它们,这导致令人讨厌的惊喜。 我能以某种方式阻止它这样做吗? 我不想改变项目的目录结构,除非它是唯一的解决scheme。

节点尝试parsing当前模块path名并将node_modules连接到它的每个父目录。 [来源] 。

您可以在项目模块的顶部重写此方法,并添加一些逻辑以从结果path数组中排除父目录。

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

受这个模块的启发

在每个文件使用的开始

 module.paths = module.paths.splice(0,1); 

这将覆盖包含所有可能的node_modulespath的node_modules数组。