为什么require('下划线')在node.js REPL执行时返回undefined?

时间:2012-05-22 23:35:18

标签: node.js include require underscore.js

当我在控制台中运行节点并输入var _ = require('underscore');时,_最终未定义。如果我将相同的代码放在一个文件中并执行它,那么下划线库将按预期包含在内。

$ node
> var _ = require('underscore');
> console.log(_)
undefined // underscore library does not load
> var async = require('async');
undefined
> console.log(async) // async library does
{ noConflict: [Function],
  nextTick: [Function],
  forEach: [Function],
...
>

但是作为node test.js执行的.js文件中的相同代码显示了两个库按预期加载。发生了什么事?

1 个答案:

答案 0 :(得分:32)

Node repl将_绑定到上次评估的输入的值;它会覆盖_中的var _ = ...;绑定。另请参阅the node.js documentation on the repl

无论取代...取代什么,都是如此:

$ node
> var _ = "any value";
undefined
> _
undefined