我遇到了 Node.js v0.10.1
的以下问题(通过一个快速示例进行了演示):
在交互式命令行中运行 Node 时:
> global.require
{ [Function: require] . . . }
> require
{ [Function: require] . . . }
当运行以下 script.js
时,我得到了意想不到的结果:
console.log(global.require); // 1.
console.log(require); // 2.
undefined // 1. `global.require` is undefined!
{ [Function: require] . . .} // 2. `require` by itself works however.
我删除了由 ...
表示的额外代码。在本地运行它以查看实际显示的全部内容。
是什么导致了这种情况?
最佳答案
Node.js 包含一个 repl允许您创建自己的 Read-Evaluate-Print-Loops 的模块(这就是 repl
的含义)。使用这个模块有一个函数 start用于创建新的 repl。
此函数接受一个options
对象,您可以在其中配置您的repl。其中一个选项称为 useGlobal
。根据此选项的文档,以下句子是有效的:
if set to
true
, then the repl will use theglobal
object, instead of running scripts in a separate context. Defaults tofalse
.
现在,当您以交互模式启动 Node.js 时,这基本上只是一个 repl,就像您可以使用 repl
模块为自己创建的那些一样。我猜想(请注意,这只是一个猜测!)Node.js 的默认 repl 已将 useGlobal
设置为 true
。
因此您有一个 global
对象,它又与全局命名空间完全相同。因此,您可以在全局命名空间中找到的所有函数,例如 require
,您将再次在 global
对象中找到。
一旦以非交互模式启动 Node.js 应用程序,就没有 repl,因此也就没有 global
对象。
这对你来说有意义吗?
关于node.js - 导致全局变量差异的原因(交互式与脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645243/