How to remove the global context from a nodejs module?

前端 未结 1 1610
余生分开走
余生分开走 2021-02-06 19:32

Any thoughts on how one would go about removing the global context from a nodejs module?

I\'m not looking for a solution to the below problem, but if you need more conte

1条回答
  •  伪装坚强ぢ
    2021-02-06 19:39

    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.

    0 讨论(0)
提交回复
热议问题