How to remove the global context from a nodejs module?

烈酒焚心 提交于 2019-12-03 04:03:12

As stated in the comments, you really need to run user-supplied modules in a separate process because an infinite loop will freeze any node process.

You should start with the VM module:

  • Read the file content (with fs.readFile, not require).
  • Define a new global object. You can choose to expose anything you want (and hide the rest).
  • Run the user code.

Here's an example:

var fs = require('fs'),
    vm = require('vm');

function runCode(fileName) {
  var code = fs.readFileSync(fileName),
      sandbox = {
        console: console,
        setTimeout: setTimeout,
        clearTimeout: clearTimeout,
        require: require,
        module: module,
        exports: exports,
        process: process,
        Buffer: Buffer
      };

  vm.runInNewContext(code, sandbox, fileName);
}

The user-supplied code will be able to access everything that I passed in the sandbox, as if it was in the global scope. In my case, I chose to expose almost everything from the real node.js global scope. You can chose what not to expose.

Also, you should check child_process.spawn if you want your solution to be secure.

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