jches
jches

Reputation: 4527

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

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?

Upvotes: 14

Views: 3057

Answers (1)

Dan D.
Dan D.

Reputation: 74655

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

Upvotes: 31

Related Questions