Nodejs vm2 - how to import scripts

2k views Asked by At

Suppose you have script A: defines a library with:

class MathFunctions { add(a, b) => { return a+b; } }

And you have script B: reuses MathFunctions somehow:

const mf = import MathFunctions;
console.log(mf.add(2, 2));

And you want to execute B in vm context, importing A.

What is the best way to do this with untrusted code?

Similar question here: https://github.com/patriksimek/vm2/issues/121

1

There are 1 answers

0
generalhenry On

The node import system (const foo = require('foo');) works by running your code through a preprocessor that wraps it in a function and passes in require, module, exports you can replicate that effect by running your code through a preprocessor as well. Fortunately there are plenty available since the browser also lacks modules. So any of the module preprocessors for browsers (eg webpack) will do the trick.

So somethings like new VM().run(webpack('./moduleB.js'))