我使用express創建了一個應用程序,並且遇到了使用module.exports的問題。我有一條路線,可以根據用戶的訂單處理用戶創建PDF的過程。爲了讓事情模塊化我已經分離我的路線功能成模塊,並要求他們在必要時,例如:節點模塊緩存
Route1.js
module.exports = function(req, res){
// route functionality
};
路線/ index.js
Route1 = require('./Route1');
router.post('/api/v1/route1', Route1);
這一直很好地保持組織的東西,但我創建了一個具有很多複雜功能的路線,並且似乎存在緩存問題。我第一次調用這個路由時,它的工作正常,但是第二次我把它叫做一個無限循環,因爲最後一個請求的一個變量是持久的,並且它永遠不會跳出循環,因爲它大於它需要等於循環退出的數量。我甚至在通過module.exports傳遞的函數的開始處重置所有變量。
要解決此問題,我不再導出路由功能,而是將其直接傳遞給路由。下面是一個例子:
作品每次
router.post('/api/v1/dostuff', function(req, res){
var count = 0;
var doSomething = function(){
// if count === something else break
// else add one to count and run this function again
}
});
作品首次
do_something.js
module.exports = function(req, res){
var count = 0;
var doSomething = function(){
// if count === something else then break out and do something else
// else add one to count and run this function again
// This works the first time but the second time
// count is persisting and it is already greater than
// the number I am checking against so it
// never breaks out of this function
}
};
路由/ index.js
var doSomething = require('./do_something.js');
// Only works as expected the first time the call is made
router.post('api/v1/dosomething', doSomething);
那麼爲什麼使用module.exports函數只能按預期工作一次?我認爲與節點模塊緩存有關。
不應該有一個如果代碼完全相同,並且'do_something.js'文件中的'module'對象沒有任何其他事情正在處理。唯一的問題可能是如果你編輯'routes/index.js'中需要的'doSomething'變量。對於一些調試想法,請查看[這個答案](http://stackoverflow.com/a/16060619/3696076)以及其他一些來自這個問題。 – cdbajorin
@cdbajorin這就是我的想法,但事實上,當它是相同的確切代碼時會發生。 –
我能想到的唯一的另一件事可能是遞歸問題(我假設基於有限描述的遞歸)?也許你可以嘗試將它切換到while循環。再次,這不應該是一個問題,但它是另一個需要遵循的調試跟蹤。 – cdbajorin