不完全正确。
- 是的,您可以分发 JSON 消息
- 热代码替换的部分有点复杂,让我解释一下......
好的,首先您显然需要进行验证等,这应该不是一个大问题。第一个小问题来自 JSON,它不允许在其中包含任何 JS 代码/函数,您可以通过将数据作为字符串发送来解决这个问题。
下一个问题,当你想替换函数/方法时,你需要确保它保持它的范围,以便新编译的函数可以访问相同的东西。
借助一些黑eval
魔法,这当然是可能的,但不要指望它会像在 Erlang 中那样自然:
var Script = process.binding('evals').Script;
var hello = 'Hello World';
var test = 42;
function Swappable(initCode) {
this.execute = function() {}
this.swap = function(code) {
this.execute = eval('func = ' + code);
}
this.swap(initCode);
}
// Note: Swappable's scope is limited, it won't inherit the local scope in which it was created...
var foo = new Swappable('function(){console.log(hello);return function(){console.log(test)}}')
var cb = foo.execute();
cb();
foo.swap('function(){console.log("Huh, old world?");return function(){console.log(test * test)}}');
var cb = foo.execute();
cb();
console.log(bar.execute());
foo.execute();
输出
Hello World
42
Huh, old world?
1764
这不能保证在所有情况和范围内 100% 有效。此外,语法很糟糕,所以我建议如果你想要热交换,请继续使用 Erlang。
记住:适合工作的正确工具。
更新
在不久的将来不会有比这更好的了,请参阅:
https ://github.com/ry/node/issues/issue/46#issue/46/comment/610779