eval
?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)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.
vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With