前端之家收集整理的这篇文章主要介绍了
node.js 动态执行脚本,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_0@node.js最近新增了虚拟机模块,其实也不能说是新增的,只是把一些内部接口暴露出来罢了,从2.x就有了。我们可以从node / src / node.js看到这些代码:
<div class="jb51code">
<pre class="brush:js;">
var Script = process.binding('evals').NodeScript;
var runInThisContext = Script.runInThisContext;
NativeModule.wrap = function(script) {
return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
};
NativeModule.wrapper = [
'(function (exports,require,module,filename,dirname) { ','\n});'
];
NativeModule.prototype.compile = function() {
var source = NativeModule.getSource(this.id);
source = NativeModule.wrap(source);
var fn = runInThisContext(source,this.filename,true);
fn(this.exports,NativeModule.require,this,this.filename);
this.loaded = true;
};
,不会影响当前作用域的对象。而runInNewContext与runInContext则能指定是上下文对象,区别是一个普通对象或一个context对象。换言之,runInNewContext与runInContext能局部影响当前作用域的对象。要与当前环境完全进行交互的话,就需要用到危险的eval。在node.js
Box;
n = 5;
sandBox = { n: n };
benchmark = function(title,funk) {
var end,i,start;
start = new Date;
for (i = 0; i < 5000; i++) {
funk();
}
end = new Date;
console.log(title + ': ' + (end - start) + 'ms');
}
var ctx = vm.createContext(sandBox);
benchmark('vm.runInThisContext',function() { vm.runInThisContext(code); });
benchmark('vm.runInNewContext',function() { vm.runInNewContext(code,sandBox); });
benchmark('script.runInThisContext',function() { script.runInThisContext(); });
benchmark('script.runInNewContext',function() { script.runInNewContext(sandBox); });
benchmark('script.runInContext',function() { script.runInContext(ctx); });
benchmark('fn',function() { fn(n); });
/**
vm.runInThisContext: 212ms
vm.runInNewContext: 2222ms
script.runInThisContext: 6ms
script.runInNewContext: 1876ms
script.runInContext: 44ms
fn: 0ms
*/