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

痞子三分冷 提交于 2019-12-11 09:48:12

问题


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? Does it keep the required function in memory? or doest it read the file anew?

Exemple:

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?


回答1:


To answer:

In node.js, how does require() work? 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. See: http://nodejs.org/api/modules.html#modules_caching




回答2:


As pointed by @Tom Grant, module are cached. 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

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()
}


来源:https://stackoverflow.com/questions/20289193/self-modifying-code-in-node-js-would-cluster-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!