I have a model with a function call of util.endsWith(str, end) but I forgot to import my util file. Normally I would expect an error like:
cannot call method 'endsWith' of undefined or something like that
but the error I am getting is:
TypeError: Object #<Object> has no method 'endsWith'
which indicates that util is defined. I did a console.log of it and found that it is the same object you get from require('util').
I certainly did not require the util module in this, and I can't find anywhere in my files where I do so (not that I would expect something require-ed in another file to be in this file).
Interestingly, util is only defined if I require this module from somewhere else; if I just run the file then util is undefined.
Is this normal?
My files are not that complicated (<100 lines each) but I have not been able to replicate it with a super basic example. Maybe it has to be a couple of levels deep.
nodejs 0.10.12
Most likely you forgot doing var util somewhere in a different module where util is being assigned to. This results in a global variable being created.
You may be leaking more global variables this way. You can get an overview which globals are being created by doing:
var oldGlobalNames = Object.keys(global)
at top of main script. Then do
console.log(_.difference(Object.keys(global), oldGlobalNames))
on bottom.
This uses the difference function from Underscore.
Or use https://github.com/aheckmann/gleak module.
Another idea: do a project-wide search (including node_modules dir) for util =. Get a sense of where util is being assigned to.
See also Node.js - why do I get leaks when testing with mocha and zombie?
I think this is a repl vs script interpreter thing. When you run the repl (either node or coffee), indeed util is available as a pre-imported module it seems. However, when you run them and pass a script argument, util is not there:
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
However, with the repl:
node
> util
{ format: [Function],
deprecate: [Function],
print: [Function],
puts: [Function],......