Why does require('underscore') return undefined when executed at the node.js REPL?

ε祈祈猫儿з 提交于 2019-11-29 17:10:44

问题


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],
...
>

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


回答1:


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


来源:https://stackoverflow.com/questions/10711561/why-does-requireunderscore-return-undefined-when-executed-at-the-node-js-rep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!