简体   繁体   中英

Nodejs vm2 - how to import scripts

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

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'))

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