【问题标题】:Can't read custom environment variables in node using config.get()无法使用 config.get() 读取节点中的自定义环境变量
【发布时间】:2019-06-01 05:31:03
【问题描述】:

我使用config library 来管理我在节点应用程序中的配置文件。

我已经在终端中导出了我的自定义环境变量 export app_password=12345

并通过

将其映射到custom-environment-variable.json文件中
{
  "mail": {
  "password": "app_password"
   }
}

当我在 index.js 文件(根模块)中使用 config.get('mail.password') 时。

我收到了error: Configuration property "mail.password" is not defined,详情如下:

/Users/tzhong/Documents/vidly- 
backend/node_modules/config/lib/config.js:203
throw new Error('Configuration property "' + property + '" is not 
defined');
^

Error: Configuration property "mail.password" is not defined
    at Config.get (/Users/tzhong/Documents/vidly- 
 backend/node_modules/config/lib/config.js:203:11)

我已经使用console.log(process.env.app_password) 检查我的自定义环境变量是否存在,并且 app_password 是否显示在终端中。

 Vidly evn is : Vidly backend -- development
 Vidly mail server is : dev-mail-server
 Mail-password is : 12345
 NODE_ENV is : undefined
 app: development
 Mongan enabled...
 Listenning 3000 port ...

我想使用console.log(config.get('mail.password')); 在终端中显示我的自定义变量而不是console.log(process.env.app_password) 有什么建议吗?

终于解决问题了: 这是一个小错误,在配置库中,用于创建自定义环境变量的文件名是严格的,文件名应该是'custom-environment-variables.json',我在'environment'上拼写错误,毕竟,感谢人们提供其他可用的包

【问题讨论】:

    标签: node.js express config


    【解决方案1】:

    将文件名重命名为带有复数“变量”的“custom-environment-variables.json”。

    【讨论】:

      【解决方案2】:

      nodejs 中执行此操作的正确方法是使用.env 文件。在根目录下创建一个.env 文件。以key=value 格式保存您的环境变量及其值,例如password=app_password

      在您的主入口点文件中,需要 dotenv 包并在需要所有模块之后加载顶部带有 dotenv.configure() 的环境变量。详情请见here

      【讨论】:

      • Hey Rajesh,感谢您的建议,但是您知道我使用配置库时我的代码有什么问题吗?
      • 我已经解决了,config.get('mail.password')的路径没问题,只是自定义的环境变量文件名应该是正确的
      【解决方案3】:

      使用 .env 而不是使用配置。只需键入 npm install --save dotenv

      即可添加
      password=some value
      

      您可以通过以下方式访问它

      require("dotenv").config();
      
      console.log(`Password is ${process.env.password}.`);
      //Output
      Password is *some value*
      

      【讨论】:

      • 你好,我想我可以在没有 dotenv 包的情况下使用 console.log(process.env.password),我想用 config 包做同样的事情。谢谢你的评论
      猜你喜欢
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2019-11-21
      • 2021-08-12
      • 1970-01-01
      • 2018-03-04
      • 2014-08-16
      • 2019-07-16
      相关资源
      最近更新 更多