Ask coding questions

← Back to all posts
How to simulate Node.js's VM module in the browser?
h
mollthecoder (37)

I'm working on an app system, and to power it I want to use Node.js's VM module to create a custom V8 runtime environment, but the system needs to be in the browser. How can I simulate VM in the browser?

Answered by Coder100 (18123) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (18123)

maybe you can consider using eval

mollthecoder (37)

@Coder100 I have but eval isn't very efficient to make a custom runtime environment.

Coder100 (18123)

yeah no it isn't how about

let f = new Function("window.a = 5;");
f();
console.log(a);

@mollthecoder

mollthecoder (37)

@Coder100 But I'm running third party code and I don't want their variables to mix with mine.

Coder100 (18123)

@mollthecoder well then
you could use like an object that you know that party won't use/won't be able to use

but overall, wouldn't this open up vulnerabilities?
And wouldn't this still happen using VM?

mollthecoder (37)

@Coder100 VM doesn't share variables in any way unless you let it. There's a slight malware risk but to be honest no one on replit knows how to do that crap from an isolated environment.

Coder100 (18123)

i see
well usually these things are accomplished like that

you send your code to a server
it evaluates it
and sends the result back

that's what you should do @mollthecoder

mollthecoder (37)

@Coder100 I'm horrible at websocket and for me this would be a last resort but I guess it's what needs to be done.

Coder100 (18123)

Well, you can't. Node.js is technically not js, in the sense that it isn't meant to be compatible with browser js.

mollthecoder (37)

@Coder100 I'm talking about a way to simulate or replace it.