nodejs'util'有时是全局的吗?
我有一个函数调用util.endsWith(str, end)
的模型,但我忘了导入我的util文件。 通常我会期望一个错误,如:
cannot call method 'endsWith' of undefined
或类似的东西
但是我得到的错误是:
TypeError: Object #<Object> has no method 'endsWith'
这表明util
已被定义。 我做了一个console.log,发现它和require('util')
。
我当然不需要在这个util模块,我不能find我的文件中的任何地方,我这样做(不是我期望在另一个文件需要在这个文件中的东西)。
有趣的是, util
只在我从别的地方需要这个模块的时候才被定义。 如果我只是运行该文件,那么util
是未定义的。
这是正常的吗?
我的文件并不复杂(每行<100行),但我还没有能够用超级基本的例子复制它。 也许它必须是深度的几个层次。
nodejs 0.10.12
很可能你忘了在util
分配给的其他模块的某个地方做var util
。 这导致一个全局variables被创build。
你可能会以这种方式泄漏更多的全局variables。 您可以通过执行以下操作来了解正在创build的全局variables:
var oldGlobalNames = Object.keys(global)
在主脚本的顶部。 然后做
console.log(_.difference(Object.keys(global), oldGlobalNames))
在底部。
这使用Underscore的difference
函数。
或者使用https://github.com/aheckmann/gleak模块。
另一个想法是:为util =
做一个项目范围的search(包括node_modules dir)。 了解util
分配的位置。
另请参阅Node.js – 为什么在使用摩卡和僵尸进行testing时会发生泄漏?
我认为这是一个repl vs脚本解释器的东西。 当你运行repl(无论是node
还是coffee
), util
看起来都可以用作预导入的模块。 但是,当您运行它们并传递脚本参数时, util
不存在:
node -e 'console.log(util)' [eval]:1 console.log(util) ^ ReferenceError: util is not defined at [eval]:1:13 at Object.<anonymous> ([eval]-wrapper:6:22) at Module._compile (module.js:456:26) at evalScript (node.js:532:25) at startup (node.js:80:7) at node.js:901:3
但是,用repl:
node > util { format: [Function], deprecate: [Function], print: [Function], puts: [Function],......