如何获取由Node vm2运行的代码的结果

最近,我一直在尝试使用由@PatrikŠimek发布的包vm2来实现沙箱执行

我试图运行一些js代码,我认为这是一个自定义的逻辑 ,我将这个逻辑存储在一个stringvariables。

我需要在沙盒环境中执行这个自定义逻辑(因为这是不可信的代码),并在实际环境中取回响应,以基于此结果继续正常的应用程序stream程。

我尝试了几种方法来获得最终结果。 自定义逻辑正在沙箱内成功执行,但我无法find一种方法将此结果发送回主进程,而是我得到的结果为undefined 。 所以,迄今为止没有任何工作。

希望我在这里得到一些答案。

自定义逻辑 (将被存储在一个string中)

function addValues(a,b){ var c = a + b; console.log('Addition of 2 values'); console.log(c); return c; } addValues(10,10); // function call 

实际执行

 // vm2 const {NodeVM} = require('vm2'); const vm = new NodeVM({ console: 'inherit', sandbox: {}, require: { external: true, builtin: ['fs','path'], root: "./", mock: { fs: { readFileSync() { return 'Nice try!';} } }, wrapper : "" } }); // Sandbox function let functionInSandbox = vm.run("module.exports = function(customLogic){ customLogic //need to execute this custom logic }); // Make a call to execute untrusty code by passing it as an argument // to sandbox environment and obtain the result var resultOfSandbox = functionInSandbox(customLogic); console.log("Result of Sandbox :"); console.log(resultOfSandbox); // undefined (need to get the result of custom logic execution) 

您需要定义一个沙箱variables。 声明一个空的对象,将其附加到你的沙箱选项,并在脚本中添加另一个属性到你的对象。 我想一个代码片段会说明一切:

 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 `; let ext = {}; const { NodeVM } = require( 'vm2' ); const vm = new NodeVM( { console: 'inherit', // pass our declared ext variable to the sandbox sandbox: { ext }, require: { external: true, builtin: ['fs', 'path'], root: './', }, } ); // run your code and see the results in ext vm.run( c, 'vm.js' ); console.log( ext );