3

In English

I'm getting some unexpected results when I try to load a module using require in the Node.js shell to play around with it (as opposed to writing a script and running that with Node). In a script, for example, I can do:

var _ = require('grunt');
grunt.registerTask(/* ...*/);

And this works fine. But when I try to do this in the Node.js shell, it first can't find the module unless I specify the node_modules directory, and then calling one of the modules' methods only works once before it stops.

In Tech-Speake

In current directory, I have the following subdirectory:

- node_modules
  - lodash
  - grunt

Now I want to play around with the Node.js shell, using one of the installed libraries:

$ node
> var _ = require('lodash');
undefined

> _ = require('./node_modules/lodash');
// Long output of function list

Now if I try to use lodash, it works once and then stops and I have to import it again:

_.reduce(/* ... */); //Works
_.reduce(/* ... */); // TypeError: Cannot call method 'reduce' of undefined
A. Duff
  • 4,097
  • 7
  • 38
  • 69

1 Answers1

12

_ as the var name does not work as Node uses it to hold the result of the last operation. Try something like:

> var l = require('lodash'); 
> l.reduce(/* ... */);
nitishagar
  • 9,038
  • 3
  • 28
  • 40
  • Thanks! I hadn't realized that! I wonder why I am able to call it `_` in a written script, then. – A. Duff Jul 30 '15 at 15:11
  • 2
    @A.Duff `_` only contains the result of the previous operation in the REPL. It wouldn't make much sense in a script; if you need access to the result, you'd assign it to something. – Aaron Dufour Jul 30 '15 at 15:23