为什么require('下划线')在node.js REPL执行时返回undefined? [英] Why does require('underscore') return undefined when executed at the node.js REPL?
问题描述
当我在控制台中运行节点并输入 var _ = require('underscore');
, _
最终未定义。如果我将相同的代码放在一个文件中并执行它,下划线库将按预期包含。
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.
$ 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],
...
>
但.js文件中的相同代码作为节点test.js执行
显示两个库按预期加载。发生了什么?
But the same code in a .js file executed as node test.js
shows both libraries loading as expected. What's going on?
推荐答案
节点repl将 _
绑定到值最后评估的输入;它会在 var _ = ...;
中覆盖 _
绑定。另请参阅关于repl 的node.js文档。
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.
无论是什么替换 ...
,都是如此:
This is true no matter what replaces ...
, for example:
$ node
> var _ = "any value";
undefined
> _
undefined
这篇关于为什么require('下划线')在node.js REPL执行时返回undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!