Running "module.exports = function(foo){...}" in Node vm2

613 Views Asked by At

I'm new to Node and the virtual machine vm2. In the documentation for the latter, it gives an example of its usage:

let functionInSandbox = vm.run("module.exports = function(who) { console.log('hello '+ who); }");
functionInSandbox('world');

Question: what is this actually doing?

Firstly, why is module.exports used here at all? Ie, why not omit it as below?

let functionInSandbox = vm.run("function(who) { console.log('hello '+ who); }");
functionInSandbox('world');

Secondly, another way of looking at it: in regular node programming, it is beginner's knowledge that require(inc) is used in one file to assign to a variable, what, in another file (chosen by inc), is assigned to module.exports. How is that different to the above usage with vm2?

Specifically: is require(...) being implicitly called in the above? How could multiple modules be defined (as above) and referred to, within one sandbox?

It's hard to know what questions to even ask - really I'm just hoping for an explanation of ways in which module.exports can be used with vm2 in ways that differ to regular node programming, highlighting differences.

0

There are 0 best solutions below