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

大城市里の小女人 提交于 2019-12-13 11:43:26

问题


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

回答1:


runInNewContext is not meant to be used as a replacement of require or eval, but instead as a way to create a sandbox environment where you can safely run other scripts.

Disadvantages are that it's slow (creation takes ~10 ms.) and takes up a couple megabytes. So no, don't use it as a require replacement.




回答2:


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.



来源:https://stackoverflow.com/questions/9867069/node-js-vm-runinnewcontext-vs-require-and-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!