2013-03-25 43 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中使用完整的文件名。