Hot Code Loading in Node.js

Node.js Web应用代码热更新的另类思路

Reading through Fever today, this post by Jack Moffitt caught my eye. In it, he discusses a hack to allow a running Python process to dynamically reload code. While the hack itself, shall we say, lacks subtlety, Jack's post got me thinking. It's true, Erlang's hot code loading is a great feature, enabling Erlang's 99.9999999% uptime claims. It occurred to me that it wouldn't be terribly difficult to implement for node.js' CommonJS-based module loader.

A few hours (and a tasty home-made Paella later), here's my answer: Hotload node branch.

Umm… What does it do?

var requestHandler = require('./myRequestHandler');

process.watchFile('./myRequestHandler', function () {
module.unCacheModule('./myRequestHandler');
requestHandler = require('./myRequestHandler');
} var reqHandlerClosure = function (req, res) {
requestHandler.handle(req, res);
} http.createServer(reqHandlerClosure).listen(8000);

Now, any time you modify myRequestHandler.js, the above code will notice and replace the local requestHandler with the new code. Any existing requests will continue to use the old code, while any new incoming requests will use the new code. All without shutting down the server, bouncing any requests, prematurely killing any requests, or even relying on an intelligent load balancer.

Awesome! How does it work?

Basically, all node modules are created as sandboxes, so that as long as you don't use global variables, you can be sure that any modules you write won't stomp on others' code, and vice versa, you can be sure that others' modules won't stomp on your code.

Modules are loaded by require()ing them and assigning the return to a local variable, like so:

var http = require('http');

The important insight is that the return value of require() is a self-contained closure. There's no reason it has to be the same each time. Essentially, require(file) says "read file, seal it in a protective case, and return that protective case." require() is smart, though, and caches modules so that multiple attempts torequire() the same module don't waste time (synchronously) reading from disk. Those caches don't get invalidated, though, and even though we can detect when files change, we can't just call require() again, since the cached version takes precedence.

There are a few ways to fix this, but the subtleties rapidly complicate matters. If the ultimate goal is to allow an already-executing module (e.g., an http request handler) to continue executing while new code is loaded, then automatic code reloading is out, since changing one module will change them all. In the approach I've taken here, I tried to achieve two goals:

  1. Make minimal changes to the existing node.js require() logic.
  2. Ensure that any require() calls within an already-loaded module will return functions corresponding to the pre-hot load version of the code.

The latter goal is important because a module expects a specific set of behaviour from the modules on which it depends. Hot loading only works so long as modules have a consistent view of the world.

To accomplish these goals, all I've done is move the module cache from a global one into the module itself. Reloading is minimised by copying parent's caches into child modules (made fast and efficient thanks to V8's approach to variable handling). Any module can load a new version of any loaded modules by first removing that module from its local cache. This doesn't affect any other modules (including dependent modules), but will ensure that any sub-modules are reloaded, as long as they're not in the parent's cache.

By taking a relatively conservative approach to module reloading, I believe this is a flexible and powerful approach to hot code reloading. Most server applications have a strongly hierarchical code structure; as long as code reloading is done at the top-level, before many modules have been required, it can be done simply and efficiently.

While I hope this patch or a modified one will make it into node.js, this approach can be adapted to exist outside of node's core, at the expense of maintaining two require() implementations.

hot code loading in nodejs的更多相关文章

  1. how to read openstack code: loading process

    之前我们了解了neutron的结构,plugin 和 extension等信息.这一章我们看一下neutron如何加载这些plugin和extension.也就是neutron的启动过程.本文涉及的代 ...

  2. Nodejs in Visual Studio Code 02.学习Nodejs

    1.开始 源码下载:https://github.com/sayar/NodeMVA 在线视频:https://mva.microsoft.com/en-US/training-courses/usi ...

  3. crossplatform---Nodejs in Visual Studio Code 02.学习Nodejs

    1.开始 源码下载:https://github.com/sayar/NodeMVA 在线视频:https://mva.microsoft.com/en-US/training-courses/usi ...

  4. Visual Studio Code 断点调试Nodejs程序跳过node内部模块(internal modules)

    Built-in core modules of Node.js can be referred to by the ‘magic name’ <node_internals> in a ...

  5. Nodejs in Visual Studio Code 01.简单介绍Nodejs

    1.开始 作者自己:开发人员,Asp.Net , html / js , restful , memcached , oracle ,windows , iis 目标读者:供自己以后回顾 2.我看No ...

  6. crossplatform---Nodejs in Visual Studio Code 01.简单介绍Nodejs

    1.开始 作者自己:开发人员,Asp.Net , html / js , restful , memcached , oracle ,windows , iis 目标读者:供自己以后回顾 2.我看No ...

  7. NodeJS错误处理最佳实践

    NodeJS的错误处理让人痛苦,在很长的一段时间里,大量的错误被放任不管.但是要想建立一个健壮的Node.js程序就必须正确的处理这些错误,而且这并不难学.如果你实在没有耐心,那就直接绕过长篇大论跳到 ...

  8. linux -- ubuntu搭建nodejs环境

    需求:在web端做一个实时性功能比较强的模块, 客户端:用websocket 服务端:node.js node.js介绍:node.js天生就是一个高效的服务端语言,可以直接使用 javascript ...

  9. 如何远程调试部署在CloudFoundry平台上的nodejs应用

    网络上关于如何本地调试nodejs应用的教程已经很多了,工具有Chrome开发者工具,Visual Studio Code,和nodejs周边的一些小工具等等. 在实际情况中,我们可能遇到本地运行良好 ...

随机推荐

  1. js手机号码正则表达式

    function checkMobile(){ var sMobile = document.mobileform.mobile.value if(!(/^1[3|4|5|8][0-9]\d{4,8} ...

  2. 手机端图片预览和缩放js

    转至:http://blog.sina.com.cn/s/blog_c342e3090102vcxu.html 1.手机端的图片选择和预览 <input type="file" ...

  3. CentOS日志列表

    anaconda/* 包含至少5个日志文件:anaccmda.log用于保存一般安装消息:anaconda.packaging.log用于保存包安装消息:anaconda.programJog用于调用 ...

  4. Vim基础教程

    一.简介 世界上只有三种编辑器,EMACS.VIM和其它. 我们所处的时代是非常幸运的,有越来越多的编辑器,相对于古老的VIM和EMACS,它们被称为现代编辑器.我们来看看这两个古董有多大年纪了: * ...

  5. Flask源码剖析详解

    1. 前言 本文将基于flask 0.1版本(git checkout 8605cc3)来分析flask的实现,试图理清flask中的一些概念,加深读者对flask的理解,提高对flask的认识.从而 ...

  6. BZOJ1222 [HNOI2001]产品加工 - 动态规划- 背包

    题解 怎么看都不像是个背包,直到我看了题解→_→, 第一次碰到这么奇怪的背包= = 定一个滚动数组$F_i$, $i$表示机器$a$用了$i$的时间, $F_i$表示机器$b$用了$F_i$的时间, ...

  7. APP UI结构-首页功能点大集锦,很干很详细

    APP UI结构的系列的文章有一段时间没有更新了,因为最近在学一些新东西和看一些新书籍,适当的给自己充电也是为了更好的输出,言归正传,今天想跟大家聊的是和首页相关的一些内容,可能有些内容最近有的小伙伴 ...

  8. 2018.10.05 NOIP模拟 阶乘(简单数论)

    传送门 签到题. 直接把所有数先质因数分解. 同时统计每一个在阶乘中会出现的质数出现的最少次数. 然后对于每一个这样的质数,我们求出满足其出现质数的m的最小值,然后求出所有m的最大值. 求m的时候可以 ...

  9. 2018.08.09 bzoj4719: [Noip2016]天天爱跑步(树链剖分)

    传送门 话说开始上文化课之后写题时间好少啊. 这道题将一个人的跑步路线拆成s->lca,lca->t,然后对于第一段上坡路径要经过的点,当前这个人能对它产生贡献当且仅当dep[s]-dep ...

  10. jaxws.xsd

    示例: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://ww ...