简体   繁体   English

在node.js中,初始程序被称为模块吗?

[英]In node.js is the initial program called as a module?

When running the command line "node index.js", is index.js treated as a module with "module scope" for variables declared within it or is it global? 运行命令行“ node index.js”时,index.js是否被视为具有“模块作用域”的模块,用于其中声明的变量还是全局变量?

For example (in index.js): 例如(在index.js中):

a = 1;     // is "a" global?
var b = 1; // is "b" global?

I know subsequent modules brought in with "require" would have all their variable declarations declared with "var" stay within the module, but I'm not sure about the initially called js file (usually named index.js) since it's not brought in with "require" (unless node does this). 我知道用“ require”引入的后续模块会将所有用“ var”声明的变量声明留在模块内,但是我不确定最初调用的js文件(通常名为index.js),因为它没有引入与“要求”(除非节点这样做)。

Node treats all script files as modules with their own " module " scope . Node将所有脚本文件都视为具有各自“ 模块 ”作用域的模块

Node has a simple module loading system. Node具有简单的模块加载系统。 In Node, files and modules are in one-to-one correspondence. 在Node中, 文件和模块是一一对应的。 [...] [...]

The module created for the entry script will be assigned to require.main : 为输入脚本创建的module 将分配给require.main

When a file is run directly from Node, require.main is set to its module . 直接从Node运行文件时,将require.main设置为其module That means that you can determine whether a file has been run directly by testing 这意味着您可以通过测试确定文件是否已经直接运行

 require.main === module 

And, you can determined what's a global by using the in operator against the global object , which all globals become a property of: 并且,您可以通过对global对象使用in运算符来确定什么是全局变量,所有全局变量都变为以下属性:

a = 1;     // is "a" global?
var b = 1; // is "b" global?

console.log('a' in global); // true
console.log('b' in global); // false

The variables declared with the initial file are treated the same as all other files. 用初始文件声明的变量与所有其他文件一样。

If you want to declare a variable as global, attach it to the GLOBAL property: 如果要将变量声明为全局变量,请将其附加到GLOBAL属性:

GLOBAL.a = 1;  // a should be available in all files

(the usual caveats about global variables apply here). (有关全局变量的通常警告适用于此)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM