正常使用VM2模块代码:
并没有返回值,和使用jsdom
const {VM,VMScript} = require('VM2');
const fs = require('fs');
const file = `${__dirname}/自己的js代码文件.js`;
const vm = new VM();
const script = new VMScript(fs.readFileSync(file),"VM2");
console.log((new VM()).run(script));
正常使用jsdom模块代码:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
加载了jsdom和接收返回值的VM2模块代码
const c = `
function addValues(a,b){
var c = a + b;
console.log('Addition of 2 values');
console.log(c);
return c;
}
// we'll define ext as a sandbox variable, so it will be available
ext.exports = addValues(10,10); // function call
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
`;
// 创建dom对象
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
let ext = {};
const {VM,VMScript} = require('VM2');
const fs = require('fs');
// const file = `${__dirname}\\自己的js代码文件.js`;
//const script = new VMScript(fs.readFileSync(file),file);
(new VM({
console: 'inherit',
// pass our declared ext variable to the sandbox
sandbox: { ext ,dom}, //这里可以直接给虚拟机require, 在vm2中创建dom对象
})).run(c)// 需要加载自己的单独文件的js用 .run(script)
console.log( ext );//返回值,相当于此处局部变量,虚拟机全局变量