Search code examples
node.jsnode-vm2

Node.js vm2 exchanging information between VM and main code using functions


I am using the vm2 module, and I have some code with two functions: get_input() for getting some data that I have, and display() for showing some data, but these functions will not be defined in that code. How do I make some sort of external function that can run the get_input() to give data from an array and output some data to my main code with the display() function? Basically I want to do this:

  • Code running in vm2 makes a get_input() call
  • Data from an array gets sent to that function
  • Data is evaluated with code in the vm2 instance
  • vm2 code makes a display() call which outputs data to another array on my main code

Any help would be appreciated.


Solution

  • The sandbox option that you pass into the vm2 constructor represents the "global" object inside the sandbox instance. You can pass functions too:

    const { VM } = require('vm2');
    
    const sandbox = {
      get_input(data) {
        return 'input:' + data;
      },
      display(data) {
        console.log('Data:', data);
      }
    }
    
    const vm = new VM({ sandbox });
    
    vm.run(`
    
    const array = [ 'foo', 'bar', 'blah' ];
    
    const ret = get_input(array[1]);
    
    display(ret);
    
    `);
    

    (output: Data: input:bar)