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

  • Is vm.runInNewContext black magic like eval ?
  • Is there a significant performance difference between require and reading the file and using vm to run it or the same under the hood (if you implemented caching, etc. and just wanted to add some variables to the context)
+4
source share
2 answers

runInNewContext not intended to replace require or eval , but instead as a way to create a sandbox environment where you can safely run other scripts.

The disadvantages are that it is slow (creation takes ~ 10 ms) and takes a couple of megabytes. Therefore, no, do not use it as a replacement for require .

+3
source

If you check the code that implements the load modules in node.js , you will see that you want to use vm.runInNewContext or vm.runInThisContext under the hood. However, require does some other additional things, such as caching a module.

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

So, require, eval and vm are all a little different, but they can all be used to load code. All of them have similar security problems if you download arbitrary code that comes from the client.

+7
source

Source: https://habr.com/ru/post/1403399/


All Articles