I'm doing some testing with node.js and several modules\libraries. For simplicity I'll focus on underscore.js.
When I run node.exe with the following source:
require("./underscore.js");
_.each({one : 1, two : 2, three : 3}, function(num, key){ console.log(num); });
I get:
C:\Dropbox\personal-work\foo\test code>node library-tests.js
node.js:208
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: _ is not defined
at Object.<anonymous> (C:\Dropbox\personal-work\foo\test code\library-tests.js:2:1)
at Module._compile (module.js:425:26)
at Object..js (module.js:443:10)
at Module.load (module.js:344:31)
at Function._load (module.js:303:12)
at Array.<anonymous> (module.js:463:10)
at EventEmitter._tickCallback (node.js:200:26)
What is also strange is that when I run it like this:
node underscore.js li开发者_StackOverflow社区brary-tests.js
It doesn't seem to do anything at all...I've even added log statements, they don't seem to execute.
I've also tried pasting in the underscore.js source into the top of my source and I get the same error...
Does anyone know what I'm doing wrong here? Thanks.
try assigning it:
var _ = require('../underscore.js');
You can see here in the annotated source code that underscore will not add itself to the global namespace if it is running in a CommonJS implementation (of which, Node.JS is one).
精彩评论