27
votes

Today, I get strange thing that after i install async in global, nodejs reports it can not find the module.following is the workflow

  1. install async

    npm install -g async

  2. make sure async exists

    npm list -g async

get this output:

/usr/local/lib
├── [email protected]
└─┬ [email protected]
  └─┬ [email protected]
    └─┬ [email protected]
      └── [email protected] 

3.try to use it.

I create a simple js file which only contains one statement:
var async=require('async');
then execute the file via node, I get exception:
Error: Cannot find module 'async'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (/lxzhu/nodejs/asynctest/test.js:1:73)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
7
Why are you installing it globally? Typically, the only things you install globally are packages where you're depending on an executable.Aaron Dufour
I would like to know why as well - regardless of best practice. I would assume it would workcyberwombat

7 Answers

29
votes

It is because you are installing async globally.

npm install async will put create a directory called node_modules, and the require lookup algorithm will find it there.

6
votes

A global installation of an NPM doesn't always mean that the module can be shared for multiple projects. This is a pretty popular misconception. You can read this blog post on nodejs.org for more information, but generally speaking, global modules are used for command line tools and other system utilities, not for modules to be used in your code.

So, ideally, you would need the modules locally for each of your projects.

4
votes

async installed globally. For that we have to create and install modules of async.

npm install async --save

this command line add files in node_modules folder.

1
votes

This worked for me:

npm uninstall async
npm install -g async
npm link async
0
votes

if dont Find Any Module like
Cannot find module 'sql' , Cannot find module 'nodemailer' then use npm install and module name which is can not found. npm install async

0
votes

One way of using globally installed modules in multiple projects is to use the npm link command

npm link will create a symlink of the globally installed package into your apps node_modules directory

-1
votes

Finally, i get answer from http://nodejs.org/api/modules.html.

After install globally, i need to put its subdirectory to NODE_PATH to make it appears in node's search path.

Also, as the document said, It is suggested to store module locally and NODE_PATH is for version compatibility and we should not use it any more.