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?
Quoted from:
https://github.com/ElemeFE/no...
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?
Every
js
文件有独立的module
,仔细看过node
官网的module
部分就能知道,每个模块也就是文件都有自己的全局变量module
,从而能通过module.exports
进行模块导出,每个文件的内容都存在一个闭包中,所以说,所谓的单独上下文其实是有的,看你怎么定义这个单独上下文,如果没有的话,CommonJS
的module
mechanism ceases to exist.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.
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
Isn’t module just the upper and lower versions?