Home  >  Q&A  >  body text

javascript - Why doesn't Node.js give each .js file a separate context to avoid scope pollution?

I saw this question in the cnode forum:

The current Node.js exposes the VM interface, allowing you to create a new js context yourself, which is quite different from front-end js. When executing external code, through Creating a new context sandbox (sandbox) can avoid context pollution:

'use strict';
const vm = require('vm');

let code =
`(function(require) {

  const http = require('http');

  http.createServer( (request, response) => {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
  }).listen(8124);

  console.log('Server running at http://127.0.0.1:8124/');
})`;

vm.runInThisContext(code)(require);

Since you can avoid pollution through a new context, why doesn't Node.js give each .js file an independent context to avoid scope pollution?

I’m really not good at learning. First of all, I didn’t understand what he asked, and secondly, how to solve this problem. I hope everyone will give you some advice. I am grateful and thank you.

Quoted from:
https://github.com/ElemeFE/no...

PHP中文网PHP中文网2713 days ago1592

reply all(5)I'll reply

  • 高洛峰

    高洛峰2017-05-16 13:47:41

    Who said Node doesn’t give each js file an independent context... Each .js file in Node, as a module, is actually encapsulated with a function. For details, please refer to the Node.js module you need to know

    Addition: I misunderstood your question. The meaning of global variables is "global". Node has this, and so does C/C++. Even Java and C# can implement "global" through static members. The big picture itself is not the problem, the question is do you really need the big picture?

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:47:41

    Every js文件有独立的module,仔细看过node官网的module部分就能知道,每个模块也就是文件都有自己的全局变量module,从而能通过module.exports进行模块导出,每个文件的内容都存在一个闭包中,所以说,所谓的单独上下文其实是有的,看你怎么定义这个单独上下文,如果没有的话,CommonJSmodule mechanism ceases to exist.

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-16 13:47:41

    The problem is actually a bit confusing. In fact, Node gives each js file an independent context, but this cannot avoid global scope pollution. In fact, this is a compromise for functionality.

    Of course, strict mode can be used to avoid global pollution caused by temporary carelessness.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:47:41

    It’s over. It seems that no one has answered this question. Please comment it yourself

    I found an answer on Zhihu that can almost answer this question. It feels almost the same

    https://www.zhihu.com/questio...

    reply
    0
  • 怪我咯

    怪我咯2017-05-16 13:47:41

    Isn’t module just the upper and lower versions?

    reply
    0
  • Cancelreply