简体   繁体   English

在node.js中自修改代码会集群工作吗?

[英]Self modifying code in node.js, would cluster work?

I am asking this since I don t have the tool or time to test this right now, but the idea is bothering me. 我问这个,因为我现在没有工具或时间来测试这个,但这个想法让我烦恼。 I ll answer this myself when I ll have the time to play with it. 当我有时间玩它时,我会自己回答这个问题。

In node.js, how does require() work? 在node.js中,require()如何工作? Does it keep the required function in memory? 它是否在内存中保留了所需的功能? or doest it read the file anew? 或者它会重新读取文件?

Exemple: 例:

launcher.js launcher.js

var cluster = require('cluster');

if (cluster.isMaster) {
    cluster.fork();
    cluster.on('exit', function () {
        cluster.fork();
    }
}
if (cluster.isWorker) {
    var self = require('self_modifying.js');
    self.start()
}

As long as self_modifying.js have a start() function which is the 'main' method, it could self-update just by modifying it s own source file, and the process.exit(0), and so restart with it new code? 只要self_modifying.js有一个start()函数,它是'main'方法,它只需修改自己的源文件和process.exit(0)就可以自我更新,所以用它重新启动新代码?

To answer: 回答:

In node.js, how does require() work? 在node.js中,require()如何工作? Does it keep the required function in memory? 它是否在内存中保留了所需的功能? or doest it read the file anew? 或者它会重新读取文件?

In node.js when a require is performed it will cache the module being loaded so each further require call will load this from memory, rather than from disk as an optimisation. 在node.js中,当执行require时,它将缓存正在加载的模块,因此每次进一步需要调用将从内存加载它,而不是从磁盘加载作为优化。 See: http://nodejs.org/api/modules.html#modules_caching 请参阅: http//nodejs.org/api/modules.html#modules_caching

As pointed by @Tom Grant, module are cached. 正如@Tom Grant指出的那样,模块是缓存的。 So you need to deference your application before starting it anew, like explained here 因此,你需要重新启动它之前,尊重你的应用程序,如解释在这里

This work, but require self_modifying.js to export a function start 这项工作,但需要self_modifying.js导出函数start

var cluster = require('cluster');

if (cluster.isMaster) {
    cluster.fork();
    cluster.on('exit', function () {
        delete require.cache[require.resolve('/full/path/to/self_modifying.js')];
        cluster.fork();
    }
}
if (cluster.isWorker) {
    var self = require('self_modifying.js');
    self.start()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM