NodeJS 示例应用程序无法启动,无法找到“配置”?

Ada*_*fin 5 javascript mongodb node.js npm express

我正在学习 node 并尝试运行我从 git 中提取的示例应用程序:

https://github.com/madhums/node-express-mongoose-demo

按照所有说明操作后,当我运行时

npm start
Run Code Online (Sandbox Code Playgroud)

我收到一个错误提示

> nodejs-express-mongoose-demo@4.0.0 start /Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo
> NODE_PATH=./config:./app/controllers NODE_ENV=development ./node_modules/.bin/nodemon server.js

20 Dec 16:45:19 - [nodemon] v1.2.1
20 Dec 16:45:19 - [nodemon] to restart at any time, enter `rs`
20 Dec 16:45:19 - [nodemon] watching: *.*
20 Dec 16:45:19 - [nodemon] starting `node --harmony server.js`
WARNING: No configurations found in configuration directory:
WARNING: /Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo/config
WARNING: See https://www.npmjs.org/package/config for more information.

module.js:340
    throw err;
          ^
Error: Cannot find module 'undefined/config/imager.js'
    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> (/Users/adam419/Desktop/Programming/JSPractice/node-express-mongoose-demo/app/models/article.js:10:20)
    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 Module.require (module.js:364:17)
20 Dec 16:45:20 - [nodemon] app crashed - waiting for file changes before starting...
Run Code Online (Sandbox Code Playgroud)

在确保我已经安装并运行了 mongodb,确保我已经安装了包括“config”在内的所有依赖项后,会发生这种情况。实际上在我运行时在节点外壳中

require('config')
Run Code Online (Sandbox Code Playgroud)

结果是不确定的。

为什么这个应用程序无法启动?

kip*_*ip2 5

我发现当NODE_CONFIG_DIR环境变量未设置时可能会发生这种情况。它告诉节点配置在哪里可以找到配置文件。默认情况下,读取正在运行的进程的 ./config 目录中的配置文件,通常是应用程序根目录。

节点配置文档建议在 CLI 或配置文件中设置此环境变量,如下所示:

process.env["NODE_CONFIG_DIR"] = __dirname;
Run Code Online (Sandbox Code Playgroud)

__dirname如果配置文件与 default.EXT 和其他配置文件位于同一文件夹中,则可以,但您可能需要将其更改为这些文件所在的实际路径。

否则,我们最终会得到:"WARNING: No configurations found in configuration directory:<PROJECT_ROOT>/config/config" 并且随后会出现如下错误:'Configuration property "some-config-key" is not defined'


小智 0

那是因为配置必须相对加载。该require('config')语句尝试在您的node_modules目录中查找名为config的模块,其中config位于根文件夹的config目录中。尝试更改require('config')require('../../config'). 那应该可以解决你的问题。