nodejs VM2虚拟机内 使用jsdom或者 获取VM2返回值

正常使用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 );//返回值,相当于此处局部变量,虚拟机全局变量
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_JackSparrow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值