NodeJs中的VM模塊詳解
什么是VM?
VM模塊是NodeJS里面的核心模塊,支撐了require方法和NodeJS的運(yùn)行機(jī)制,我們有些時(shí)候可能也要用到VM模板來做一些特殊的事情。
通過VM,JS可以被編譯后立即執(zhí)行或者編譯保存下來稍后執(zhí)行(JavaScript code can be compiled and run immediately or compiled, saved, and run later.)
VM模塊包含了三個(gè)常用的方法,用于創(chuàng)建獨(dú)立運(yùn)行的沙箱體制,如下三個(gè)方法
vm.runInThisContext(code, filename);
此方法用于創(chuàng)建一個(gè)獨(dú)立的沙箱運(yùn)行空間,code內(nèi)的代碼可以訪問外部的global對象,但是不能訪問其他變量
而且code內(nèi)部global與外部共享
var vm = require("vm");
var p = 5;
global.p = 11;
vm.runInThisContext("console.log('ok', p)");// 顯示global下的11
vm.runInThisContext("console.log(global)"); // 顯示global
console.log(p);// 顯示5
vm.runInContext(code, sandBox);
此方法用于創(chuàng)建一個(gè)獨(dú)立的沙箱運(yùn)行空間,sandBox將做為global的變量傳入code內(nèi),但不存在global變量
sandBox要求是vm.createContext()方法創(chuàng)建的sandBox
var vm = require("vm");
var util = require("util");
var window = {
p: 2,
vm: vm,
console: console,
require: require
};
var p = 5;
global.p = 11;
vm.createContext(window);
vm.runInContext('p = 3;console.log(typeof global);', window); // global是undefined
console.log(window.p);// 被改變?yōu)?
console.log(util.inspect(window));
vm.runInNewContext(code, sandbox, opt);
這個(gè)方法應(yīng)該和runInContext一樣,但是少了創(chuàng)建sandBox的步驟
比較

更為復(fù)雜的情形
如果runInContext里面執(zhí)行runInThisContext會是怎么樣,runInThisContext訪問到的global對象是誰的?
如下代碼將會怎么執(zhí)行?
var vm = require("vm");
var util = require("util");
var window = {
p: 2,
vm: vm,
console: console,
require: require
};
window.global = window;
var p = 5;
global.p = 11;
vm.runInNewContext('p = 3;console.log(typeof global);require(\'vm\').runInThisContext("console.log(p)");', window);
runInThisContext里面的代碼可以訪問外部的global對象,但外面實(shí)際上不存在global對象(雖然有,但本質(zhì)不是global對象),只要記住一點(diǎn),runInThisContext只能訪問最頂部的global對象就OK了
執(zhí)行結(jié)果如下
object (global存在)
11 (頂部global的p)
相關(guān)文章
koa+jwt實(shí)現(xiàn)token驗(yàn)證與刷新功能
這篇文章主要介紹了koa+jwt實(shí)現(xiàn)token驗(yàn)證與刷新功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
基于node搭建服務(wù)器,寫接口,調(diào)接口,跨域的實(shí)例
今天小編就為大家分享一篇基于node搭建服務(wù)器,寫接口,調(diào)接口,跨域的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
詳解使用抽象語法樹AST實(shí)現(xiàn)一個(gè)AOP切面邏輯
這篇文章主要為大家介紹了使用抽象語法樹AST實(shí)現(xiàn)一個(gè)AOP切面邏輯的簡單方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
NodeJS設(shè)計(jì)模式總結(jié)【單例模式,適配器模式,裝飾模式,觀察者模式】
這篇文章主要介紹了NodeJS設(shè)計(jì)模式,結(jié)合實(shí)例形式總結(jié)分析了nodejs單例模式,適配器模式,裝飾模式,觀察者模式的概念、原理與具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-09-09
Node.js Continuation Passing Style( CPS與
這篇文章主要介紹了Node.js Continuation Passing Style,將回調(diào)函數(shù)作為參數(shù)傳遞,這種書寫方式通常被稱為Continuation Passing Style(CPS),它的本質(zhì)仍然是一個(gè)高階函數(shù),CPS最初是各大語言中對排序算法的實(shí)現(xiàn)2022-06-06

