6

I ran the following code to install the underscore js module:

npm install -g underscore

I then tried to access it via the node console, but I get the following error:

node
> __ = require('underscore');
Error: Cannot find module 'underscore'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:362:17)
  at require (module.js:378:17)
  at repl:1:6
  at REPLServer.self.eval (repl.js:109:21)
  at rli.on.self.bufferedCmd (repl.js:258:20)
  at REPLServer.self.eval (repl.js:116:5)
  at Interface.<anonymous> (repl.js:248:12)
  at Interface.EventEmitter.emit (events.js:96:17)

Why doesn't this example work?

GSto
  • 41,512
  • 37
  • 133
  • 184
  • What's in your `NODE_PATH` environment variable? Where was underscore installed? Did the installation succeed? – Aaron Dufour Apr 02 '13 at 16:47
  • Possible duplicate of https://stackoverflow.com/questions/15636367/nodejs-require-a-global-module-package The solution in that answer is the same as the one given below – paul May 24 '18 at 19:32
  • Possible duplicate of [NodeJS require a global module/package](https://stackoverflow.com/questions/15636367/nodejs-require-a-global-module-package) – paul May 24 '18 at 19:33

2 Answers2

6

I don't really know why, but it fails indeed (when installing underscore globally, as you have done).

If you install it without -g, it should work (be careful, however, as '_' is already used by Node REPL to hold the result of the last operation, as explained here: Using the Underscore module with Node.js

Do you really need to install it globally?

Community
  • 1
  • 1
Javo
  • 627
  • 6
  • 4
  • 1
    Ok, didn't remember that, if you install modules globally, then when requiring them, you have to require them using require('{prefix}/module') As explained here: http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/ In my case, as I use nvm, the module was being installed at .nvm/$VERSION/lib/node_modules so adding that route to the require in Node REPL just worked. Hope it helps!! – Javo Apr 02 '13 at 17:07
4

I just had the same problem

$ export NODE_PATH=/usr/local/share/npm/lib/node_modules

sorted it out for me; this obviously depends on your platform and where npm has installed it. Also, as mentioned in Javo's answer, don't name it _ in the REPL.

Leinster
  • 401
  • 3
  • 5
  • Thanks. I am using nvm and node v4.2.1 and I had to `export NODE_PATH=~/.nvm/versions/node/v4.2.1/lib/node_modules/` – mc9 Nov 05 '15 at 00:57