Node.js는 최근 가상 머신 모듈을 추가했습니다. 사실, 그것은 새로운 것이라고 말할 수는 없습니다. 2.X에서 사용할 수있는 일부 내부 인터페이스 만 노출됩니다. Node/Src/Node.js에서 이러한 코드를 볼 수 있습니다.
var script = process.binding ( 'evals'). 노드 스크립트; var runinthiscontext = script.runinthiscontext; nativeModule.wrap = function (script) {return nativeModule.wrapper [0] + script + nativemodule.wrapper [1]; }; nativemodule.wrapper = [ '(함수 (내보내기, 요구, 모듈, __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; };그것의 스크립트 객체는 요구 사항 ( 'vm')에 의해 반환 된 객체와 매우 유사하지만 본질적으로 VM 모듈은 스크립트 객체의 캡슐화입니다.
var script = process.binding ( 'evals'). nodescript; console.log (script)/** {[function : modescript] createContext : [function], runincontext : [function], runinthiscontext : [function], runinnewContext : [function]}*/console.log (re20 : {vm ') createContext : [function], runinContext : [function], runinthiscontext : [function], runInnewContext : [function]}, createScript : [function], createContext : [function], runInconText : [function], runInthiscOntext : [function], runinNewContext : [function]}그중에서도 Runinthiscontext는 새로운 환경에서 코드를 실행하는 것과 동일하며 현재 범위의 객체에 영향을 미치지 않습니다. runinNewContext 및 RunInconText는 컨텍스트 객체로 지정할 수 있으며 차이는 일반 객체 또는 컨텍스트 객체입니다. 다시 말해, RuninNewContext 및 RunInconText는 현재 범위의 객체에 로컬에 영향을 줄 수 있습니다. 현재 환경과 완전히 상호 작용하려면 위험한 EVAL이 필요합니다. Node.js와 함께 제공되는 로딩 시스템에서는 분명히 용기가 없으며 Runinthiscontext를 사용합니다. 또한 사용자의 JS 파일의 내용을 레이어 (nativeModule.wrap)로 감싸는 등 많은 작업을 수행했습니다. 유일한 이점은 동기화가 사용되어 코드를 훨씬 쉽게 작성할 수 있다는 것입니다.
Github에서 일부 사람들은 이러한 스크립트를 동적으로 실행하는 이러한 방법의 성능을 비교했습니다.
var vm = require ( 'vm'), code = 'var square = n * n;', fn = new 함수 ( 'n', code), script = vm.createscript (code), 샌드 박스; n = 5; 샌드 박스 = {n : n}; 벤치 마크 = 기능 (제목, 펑크) {var end, i, start; 시작 = 새 날짜; for (i = 0; i <5000; i ++) {funk (); } end = 새 날짜; console.log (title + ':' + (종료 - 시작) + 'ms');} var ctx = vm.createcontext (샌드 박스); 벤치 마크 ( 'vm.runinthiscontext', function () {vm.runinthiscontext (코드);}); 벤치 마크 ( 'vm.runinnewcontext', function () 샌드 박스); 벤치 마크 ( 'script.runinthiscontext', function () {script.runinthiscontext ();}); 벤치 마크 ( 'script.runinnewContext', function () {script.runinNewContext ', function () {script.runinwcontext (); }); Benchmark ( 'script.runinnewContext', function () {script.RuninNewContext (Sandbox);}); Benchmark ( 'script.runinconText', function () {script.runinconText (ctx);}); 벤치 마크 ( 'fn', fn (n); });/** vm.runinthiscontext : 212msvm.RuninNewContext : 2222msScript.RuninThisconText : 6msScript.RuninNewContext : 1876msScript.RuninContext : 44msfn : 0ms*/이것으로부터 우리는 V8 방법이 완전한 승리임을 알 수 있습니다!
위는이 기사의 전체 내용입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.