![](/img/trans.png)
[英]Where are functions and variables exported in Node.js module.exports?
[英]Node.js: Do Variables in Module.exports Global?
我正在嘗試全局聲明變量“ calculator”,以便不會為每個請求創建變量,因為這對代碼性能不利。 我的解決方案是在module.exports塊內聲明它,並將其傳遞給使用它的方法。 這樣可以保證不會根據請求創建“計算器”嗎?
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);
};
是。 您隨require()
包含的文件被加載並執行一次,然后被緩存。 但是,我不太在乎性能。 較小的函數會被快速解析,對於較大的函數,無論如何都要將它們放在單獨的文件中是有意義的。 在這種情況下,我將專注於代碼質量而不是性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.