缺少节点模块的Heroku应用程序错误(但它看起来像它已安装)

时间:2015-12-14 17:44:46

标签: javascript node.js heroku

我试图使用节点和Heroku运行,但我已经陷入了早期的障碍。在this guide之后,我无法在本地看到我的Heroku应用。正在运行

heroku local web

并转到localhost:5000会产生以下错误:

  

错误:无法找到模块' ejs'

我按照建议here尝试了npm install ejs -g,看起来有效npm list -g --depth=0表示安装了ejs@2.3.4。我该怎么做才能解决这个奇怪的错误?

1 个答案:

答案 0 :(得分:2)

npm install -g installs the package globally.

node cannot find globally installed packages when you reference them with

var ejs = require('ejs')

You need to install with npm install --save ejs. This will install the package into the local node_modules directory and save it to your package.json

This is because when node looks for a package where the path doesn't start with a . or a / it looks in the current directory's node_modules directory for a directory named after the package. Then it goes up a directory and does the same, keeping looping until it reaches the root of your file system.

e.g. if you're in /users/thomas/src/myproject it'll look for:

/users/thomas/src/myproject/node_modules/ejs
/users/thomas/src/node_modules/ejs
/users/thomas/node_modules/ejs
/users/node_modules/ejs
/node_modules/ejs

If it does not exist in one of those places, it will not be found.

(There are some deprecated ways that you can have it look in other places as well, but these are not recommended since it involves using an environment variable which can be difficult to remember to set on deployed machines)

Additionally if you're using heroku, you need to have the package listed in the dependencies of your package.json file in order for heroku to know to install it. npm install -g does not add an entry to your package.json

Some recommendations, however.

  1. Don't use EJS. There are better (and currently maintained) templating packages out there. We use EJS in an old legacy system and it's more frustrating than anything.
  2. Don't ever install packages with -g unless you truly want the tool to be global. Most of the time you want it local to your project.