问题
I have centOS: When I try to run an node.js app that requires express, I get the following error:
module.js:340
throw err;
^
Error: Cannot find module 'express'
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.<anonymous> (/var/www/tipsterPro/index.js:2:15)
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)
I verified that express is in the node_modules directory:
root@myServer [/usr/local/lib/node_modules]# ls
./ ../ express/ express-generator/ forever/ n/ npm/ pm2/ supervisor/
I found a couple of postings stating to install express in the top directory of the node.js project. Is there a way to not have to install express in every project I have? There should be a way to point it to the install directory.
Additional info:
I installed node and express globally.
I also installed express-generator using: npm install -g express-generator
.
BTW: node modules are installed in this location (not sure if correct): /usr/local/lib/node_modules
I ended up installing locally, after some reading about pros and cons of express local versus global installation it might be better if I install express locally. Once I installed locally it ran successfully.
回答1:
The node module lookup algorithm looks like this (from Node.js in Action):
So if you have the module installed in node_modules at the root directory of your project, it will be found in every subdirectory and file. As you can see at the last point of the diagram, you can specify a search directory by setting the NODE_MODULES environment variable. When you globally install express it may be located somewhere like /usr/local/bin/express
. You could set the NODE_MODULES directory when launching your app using
NODE_MODULES=/usr/local/bin/ node app.js
回答2:
As you have guessed, there is indeed a solution to your issue.
You need to install express globally. That is instead of running npm install express
you run:
sudo npm install -g express
- The sudo is needed to get write access to the global location.
- Flag
-g
stands for global installation. You can use it on any module.
This is not panacea though, some projects might require very specific versions, thus having a single install is not an option. For such projects you still have to install express locally for the project. But in your case, I believe having a global install is sufficient.
回答3:
Node searches upward in the directory hierarchy for packages.
An absurd answer is to do this
# cd /
# npm install express
That will set up /node_modules ...
来源:https://stackoverflow.com/questions/24562283/do-i-need-to-install-express-in-every-project-directory