Javascript Node.js重新加载模块错误
我以这种方式重新加载模块:Javascript Node.js重新加载模块错误,javascript,node.js,require,long-running-processes,Javascript,Node.js,Require,Long Running Processes,我以这种方式重新加载模块: require('./module.js'); // require the module delete require.cache('/module.js'); // delete module from cache require('/module.js'); // re-require the module 但如果模块包含以下内容,则会出现问题: setInterval(function(){ con
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
,但最后一个模块不会关闭
有没有办法知道每个模块(长时间)运行的函数,以便在再次需要之前停止它们?或者有什么建议我怎样才能使这项工作成功
我愿意接受任何疯狂的想法。我只需设置一个对间隔的引用,并公开一个方法来阻止它,就像:
var interval = setInterval(function () {
console.log('hello');
}, 1000);
var clearInt = clearInterval(interval);
我不认为你可以钩到任何事件,因为你只是删除一个引用。如果它不再存在,它将重新加载。在执行此操作之前,请调用clearInt函数。我只需设置一个对间隔的引用,并公开一个方法以停止它,如下所示:
var interval = setInterval(function () {
console.log('hello');
}, 1000);
var clearInt = clearInterval(interval);
我不认为你可以钩到任何事件,因为你只是删除一个引用。如果它不再存在,它将重新加载。执行此操作之前,请调用clearInt函数。您可以在主应用程序中创建
IntervalRegistry
:
在您的模块中,您将注册在此创建的间隔:
// 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];
请记住,模块以其完整文件名存储在
require.cache
中。您可以在主应用程序中创建IntervalRegistry
:
在您的模块中,您将注册在此创建的间隔:
// 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];
请记住,模块以其完整文件名存储在
require.cache
中。这只是一个猜测,但您可以在一个内存中加载模块
完成后,请使用domain.dispose()清除计时器:
dispose方法销毁域,并尽最大努力尝试
清除与域关联的任何和所有IO。溪流
中止、结束、关闭和/或销毁定时器被清除。
显式绑定的回调不再被调用。任何错误事件
因此而引发的错误将被忽略
这只是一个猜测,但是您可以在一个内存中加载模块 完成后,请使用domain.dispose()清除计时器: dispose方法销毁域,并尽最大努力尝试 清除与域关联的任何和所有IO。溪流 中止、结束、关闭和/或销毁定时器被清除。 显式绑定的回调不再被调用。任何错误事件 因此而引发的错误将被忽略