Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS vm.runInNewContext() vs require() and eval()

Tags:

node.js

eval

v8

  • Is vm.runInNewContext considered black magic like eval?
  • Is there a significant performance difference between require and reading a file and using vm to run it or is the the same under the hood (if you implemented caching etc and just wanted to add some variables to the context)
like image 692
Christopher Tarquini Avatar asked Mar 26 '12 05:03

Christopher Tarquini


People also ask

How can ECMAScript be used natively in node?

Enabling# Node.js has two module systems: CommonJS modules and ECMAScript modules. Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader.

What is vm2?

vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.

Does node JS run in a VM?

The vm module in Node. js is available by default — no need for NPM. Once it is implemented, we can define the actual JS code we want to execute. To execute the code in the VM, we call runInThisContext .

What is VM in node JS?

The node:vm module enables compiling and running code within V8 Virtual Machine contexts. The node:vm module is not a security mechanism. Do not use it to run untrusted code. JavaScript code can be compiled and run immediately or compiled, saved, and run later.


1 Answers

If you check out the code that implements loading Modules in node.js, you'll see that require uses vm.runInNewContext or vm.runInThisContext under the hood. The require however, does some other extra things, like caching the module.

The node documentation shows how the behavior is similar and different between the vm commands and eval.

So, require, eval and vm are all a little bit different, but all can be used to load code. They all have similar security issues if you are loading arbitrary code that comes from the client.

like image 60
James Kingsbery Avatar answered Sep 16 '22 14:09

James Kingsbery