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

时间:2022-03-13 22:29:08

When I run node in my console and type var _ = require('underscore');, _ ends up undefined. If I put the same code in a file and execute it, the underscore library gets included as expected.

当我在我的控制台中运行节点并输入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],
...
>

But the same code in a .js file executed as node test.js shows both libraries loading as expected. What's going on?

但是作为节点test.js执行的.js文件中的相同代码显示两个库按预期加载。这是怎么回事?

1 个解决方案

#1


32  

The Node repl binds _ to the value of the last evaluated input; which overwrites your _ binding in var _ = ...;. Also see the node.js documentation on the repl.

Node repl将_绑定到最后一次计算输入的值;它会在var _ = ...;中覆盖你的_ binding。另请参阅repl上的node.js文档。

This is true no matter what replaces ..., for example:

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

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

#1


32  

The Node repl binds _ to the value of the last evaluated input; which overwrites your _ binding in var _ = ...;. Also see the node.js documentation on the repl.

Node repl将_绑定到最后一次计算输入的值;它会在var _ = ...;中覆盖你的_ binding。另请参阅repl上的node.js文档。

This is true no matter what replaces ..., for example:

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

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