2013-03-25 75 views
0

我重裝一個模塊是這樣的:Node.js的重裝模塊錯誤

require('./module.js');    // require the module 
delete require.cache('/module.js'); // delete module from cache 
require('/module.js');    // re-require the module 

但如果該模塊包含像這樣存在一個問題:

setInterval(function(){ 
    console.log('hello!'); 
}, 1000); 

我每次重裝模塊將調用新的setInterval,但最後一個未關閉。

有什麼方法可以知道每個模塊的(長)運行功能,所以我可以在我再次需要它之前阻止它們?或者有什麼建議,我該如何做這項工作?

我接受任何瘋狂的想法。

回答

4

這只是一個瘋狂的猜測,但你可能能夠加載模塊在domain

當您完成使用domain.dispose()來清除定時器:

的Dispose方法破壞域,並作出最大努力設法 清理了與相關的任何及所有IO該域名。流 被中止,結束,關閉和/或銷燬。 定時器被清除。 不再調用明確綁定的回調。任何由於此而引發的錯誤事件 都將被忽略。

0

我會簡單地設置間隔的引用,爲了揭露的方法來阻止它這樣的:

var interval = setInterval(function() { 
    console.log('hello'); 
}, 1000); 

var clearInt = clearInterval(interval); 

我不認爲你可以連接到任何事件,你只是刪除的參考。如果它不存在,它會重新加載。在執行此操作之前,請調用clearInt函數。

0

你可以在主應用程序創建一個IntervalRegistry

global.IntervalRegistry = { 
    intervals : {}, 
    register : function(module, id) { 
     if (! this.intervals[module]) 
     { 
     this.intervals[module] = []; 
     } 
     this.intervals[module].push(id); 
    }, 
    clean  : function(module) { 
     for (var i in this.intervals[module]) 
     { 
     var id = this.intervals[module][i]; 
     clearInterval(id); 
     } 
     delete this.intervals[module]; 
    } 
    }; 

在你的模塊,你就註冊的時間間隔創建有:

// module.js 
IntervalRegistry.register(__filename, setInterval(function() { 
    console.log('hello!'); 
}, 1000)); 

當它的時間來清理,調用此:

var modulename = '/full/path/to/module.js'; // !!! see below 
IntervalRegistry.clean(modulename); 
delete require.cache[modulename]; 

請記住,模塊是s在require.cache中使用完整的文件名。