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

Nis*_*gar 5 node.js nodevm node-vm2

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

\n\n

我正在尝试运行一些 js 代码,我认为它是自定义逻辑,我将此逻辑存储在一个字符串变量中。

\n\n

我需要在沙箱环境中执行此自定义逻辑(因为这是不可信代码),并在实际环境中获取响应,以便根据此结果继续正常的应用程序流程。

\n\n

我尝试了多种方法才得到最终结果。自定义逻辑在沙箱内成功执行,但我无法找到一种方法将此结果发送回主进程,但我得到的结果为未定义。因此,到目前为止,还没有任何效果。

\n\n

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

\n\n

自定义逻辑(将存储在字符串中)

\n\n
function addValues(a,b){\n   var c = a + b;\n   console.log(\'Addition of 2 values\');\n   console.log(c); \n   return c;\n}\n\naddValues(10,10); // function call\n
Run Code Online (Sandbox Code Playgroud)\n\n

实际实施

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

lum*_*mio 2

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

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 );
Run Code Online (Sandbox Code Playgroud)