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:
get_input()
calldisplay()
call which outputs data to another array on my main codeAny 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
)