【问题标题】:How to get the result of the code which is run by Node vm2如何获取 Node vm2 运行的代码的结果
【发布时间】:2017-08-29 13:37:27
【问题描述】:

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

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

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

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

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

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

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)

【问题讨论】:

    标签: node.js node-vm2 nodevm


    【解决方案1】:

    您需要定义一个沙盒变量。声明一个空对象,将其附加到您的沙箱选项中,然后在您的脚本中为您的对象添加另一个属性。我猜代码 sn-p 会说明一切:

    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 );
    

    【讨论】:

    • 感谢您的回复。您的建议非常适合检索执行结果。但是,在我的例子中,Custom Logic 是动态获取的,因此不能修改。例如:“无法按照您的建议将沙箱变量(ext)分配给函数调用”(即:ext.exports = addValues(10,10);)。有没有其他方法可以让我按原样执行逻辑并检索其结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多