2014-07-18 41 views
0

我試圖在全局聲明變量'calculator',以便它不會爲每個請求創建,因爲這對代碼性能不利。我的解決方案是在module.exports塊中聲明它,並將它傳遞給使用它的方法。這將保證'計算器'不會根據請求創建嗎?Node.js:在Module.exports Global中執行變量嗎?

var awesomeModule = require(__dirname + '/../awesomeModule'); 

var calculate = module.exports = { 
     method: 'get', 
     route: '/get_calulation', 
     handler: function(request, response, next) { 
      var id = request.query.id; 
      var calculatorVersion = request.query.calculatorVersion; 
      var calculator = awesomeModule.getCalculator(calculatorVersion); 

      doCalculation(id, calculator); 

     } 
}; 

var doCalculation= calculate .doCalculation= function(id, calculator) { 
     calculator(id); 
}; 
+0

與您的問題無關,但您不需要'__dirname'。模塊路徑已經相對於js文件,而不是當前的工作目錄。 – loganfsmyth

回答

2

是的。包含在require()中的文件將被加載並執行一次,然後進行緩存。 但是,我不會在意性能太多。較小的函數可以快速解析並獲得更大的函數,但將它們放入單獨的文件是有意義的。在這種情況下,我會專注於代碼質量而不是性能。