简体   繁体   中英

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM