vm 沙箱模块

306 阅读1分钟

\

vm 沙箱模块

\

  • runInThisContext:在全局上下文中执行

一个node.js文件中的作用域是使用函数function (exports,module,require,__direname,filename){ }包裹过后的,也即:

\


const vm = require("vm");

global.a = 1;

var b = 2;

\


vm.runInThisContext("console.log(typeof a)"); //number

vm.runInThisContext("console.log(typeof this.a)"); //number this相当于global

vm.runInThisContext("console.log(typeof b)"); //undefined

vm.runInThisContext("console.log(typeof require)"); //undefined

\

  • runInNewContext是在一个全新的作用域下执行,也即拿不到global的属性

\


const vm = require("vm");

global.a = 1;

var b = 2;

\


let obj = {c:3}

vm.runInNewContext("a = typeof a",obj);

vm.runInNewContext("b = typeof b",obj);

vm.runInNewContext("global = typeof global",obj);

vm.runInNewContext("c = typeof c",obj);

\


console.log(obj);//{ c: 'number', a: 'undefined', b: 'undefined', global: 'undefined' }