In node, why does require() fail to find a module I just installed with npm?


In a case that looks similar to this problem, I have installed a module with npm, but require('module') can't find it.

my-machine:projectname me$ npm install express-csrf
npm info it worked if it ends with ok
npm info version 0.2.1
npm info install express-csrf@0.3.3
npm info activate express-csrf@0.3.3
npm info build Success: express-csrf@0.3.3
npm ok

So far, so good. But then...

my-machine:projectname me$ node
> require('express-csrf')
Error: Cannot find module 'express-csrf'
at Function._resolveFilename (module.js:317:11)
at Function._load (module.js:262:25)
at require (module.js:346:19)
at [object Context]:1:1
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)

npm says the package is there:

my-machine:projectname me$ npm ls express-csrf
npm info it worked if it ends with ok
npm info version 0.2.1
express-csrf@0.3.3             active installed
npm ok

Note that the new module doesn't appear in the /usr/local/lib/node directory, but it does appear under /usr/local/lib/node/.npm

my-machine:projectname me$ ls /usr/local/lib/node/express-csrf*
ls: /usr/local/lib/node/express-csrf*: No such file or directory
my-machine:projectname me$ ls /usr/local/lib/node/.npm/express-csrf*
0.3.3   active

Update: I should mention that everything works when I fully qualify the path in the require statements like so:

Problem courtesy of: MW Frost


Upgrade npm.

Your problem is that require() doesn't search the .npm folder.

You can solve this by upgrading npm so that it places files in the right spots. Alternatively, you can install your modules manually in a folder in the root of your project and require('../mymodule')

Solution courtesy of: Chris Biscardi


If you are on windows use:

export NODE_PATH="C:\Users\IMarek\AppData\Roaming\npm\node_modules"
Discussion courtesy of: Mark Karwowski

This recipe can be found in it's original form on Stack Over Flow.