2017-03-16 52 views
0

我正在开发我的第一个NodeJS项目。当我在书本上和互联网上阅读时,我开始以古典的方式构建模块。 随着项目开始增长,我决定将模块拆分成小型可重用组件。这导致我在文件的顶部有大量的require,并且有时候会有解决循环依赖的风险。而且,这种方法并不适合测试,因为我必须要求所有依赖项进行测试。我问其他开发人员更好的方法来解决这个问题,他们中的大多数人建议我使用依赖注入和函数构造函数。作为构造函数的节点模块

假设我有ModuleA和ModuleB, ModuleC同时需要ModuleA和ModuleB。而不是要求这些模块在页面的顶部,我应该将它们作为参数在构造函数中传递。 例如

module.exports = function ModuleC(moduleA, moduleB) { 
//module implementation here.... 
function doSomething() {} 
return { 
    doSomething 
} 
} 

这种方法的问题,起初看起来很不错,是在应用程序的主入口点我有权要求和实例的所有模块通过。

const ModuleA = require("./moduleA"); 
const ModuleB = require("./moduleB"); 
const ModuleC = require("./moduleC"); 

const moduleA = new ModuleA(); 
const moduleB = new ModuleB(); 


const moduleC = new ModuleC(moduleA, moduleB); 
moduleC.doSomething(); 

现在只有3个模块,我不得不编写7行代码才能使用模块的功能。如果我有20个模块与应用程序的主要入口点一起工作将是一场噩梦。

我想这不是最好的方法,即使使用这种方法,测试也不容易。

所以,我要求你建议/解释我在开始探索NodeJS单词时完成我发现的这个简单任务的最佳方式,也许比它更难。谢谢。

回答

0

如果您将所有代码放入单个文件中,也可以实现代码重用性。创建更小的模块并不是唯一的解决方案。考虑写在文件allLogic.js(let)中的以下代码。

var allFunctions = function(){ }; 
var allFunctionsProto = allFunctions.prototype; 

allFunctionsProto.getJSONFile = function(fileName){ 
    var that = this; //use 'that' instead of 'this' 
    //code to fetch json file 
}; 


allFunctionsProto.calculateInterest = function(price){ 
    var that = this; //use 'that' instead of 'this' 
    //code to calculate interest 
}; 

allFunctionsProto.sendResponse = function(data){ 
    var that = this; //use 'that' instead of 'this' 
    //code to send response 
}; 

//similary write all of your functions here using "allFunctionsProto.<yourFunctionName>" 

module.exports = new allFunctions(); 

每当我需要得到任何JSON文件我知道逻辑得到JSON文件已经写在allLogic.js文件,所以我需要这个模块,并使用如下。

var allLogic = require('../path-to-allLogic/allLogic.js'); 
allLogic.getJSON(); 

这种方法比为每项工作创建大量模块要好得多。当然,如果模块时间更长,您可以创建新模块,但在这种情况下,您需要考虑问题分离,否则循环依赖将困扰您。

当你正在使用你moduleCmoduleAmoduleB,如果你把所有的moduleA,moduleB和moduleC代码的单个模块中,我曾指出,你可以参考里面的功能和所有的独立功能模块使用that和那些也需要后才可用。