8

我正在运行config@1.30.0,我试图从环境变量中获取设置.\config\custom-environment-variables.json不起作用。但是,它读起来还.\config\default.json不错。

.\config\custom-environment-variables.json

{
  "key": "app_key"
}

.\config\default.json

{
  "key": "defaultKey"
}

跑步

const config = require('config');
console.log(config.get('key'))

总是打印

defaultKey

key但是当我将config/default 中的属性设置为空字符串时,什么也不打印。我该如何解决这个问题?

我试过的

  1. 每当我使用 set app_key=newKey 设置环境变量时打开一个新控制台
  2. 手动设置环境
4

6 回答 6

15

配置文件名与您在启动节点时使用的 NODE_ENV 环境变量有关。

该模块的目的是为您要部署到测试、暂存、生产环境的每种类型的环境提供一个配置文件。如果没有设置或找不到文件,默认接管

例如,对于您将拥有的测试和登台环境。

config/default.json

{
  "key": "default_key"
}

config/test.json

{
  "key": "test_key"
}

config/production.json

{
  "key": "prod_key"
}

app.js

var config = require('config')
console.log(config.key)

然后,如果您使用与配置目录中的文件同名的不同 NODE_ENV 运行,您将获得不同的密钥

node app.js // output default_key
NODE_ENV=test node app.js // output test_key
NODE_ENV=production node app.js // output prod_key

您质疑使用文件引用自定义环境变量config/custom-environment-variables.json此文件将使您能够在运行 node.js 时使用设置的环境变量覆盖其中一个文件中的值。当您无法提交变量(例如数据库密钥)但可能希望在同一位置访问所有配置时,这很有用。

例如

{
  "key": "SECURE_DATABASE_KEY"
}

然后使用新的配置文件再次运行相同的程序:

NODE_ENV=production node app.js // output prod_key
SECURE_DATABASE_KEY=asldfj40 NODE_ENV=production node app.js // output asldfj40
于 2018-05-31T09:00:12.057 回答
8

我遇到了类似的问题,发现如果我打开新的终端窗口并在我运行的同一窗口中重新启动服务器export some_secret=immasecret,那么应​​用程序不会崩溃并且some_secret可以访问变量。我以前一直试图在另一个窗口中运行节点时访问该变量。

于 2018-06-08T18:33:47.827 回答
4

此问题与 VSCODE 编辑器集成终端有关

We have also struggled a lot with this issue initially, but the issue is that you might be using the **integrated terminal** that comes with *VSCODE* there is an issue with that, please try to use some external terminals like *cmder* or cmd prompt that comes with windows you will get the output as you are expecting.

使用外部终端或 CMD 提示执行代码

于 2020-04-12T08:44:17.017 回答
2

一个解决方案是custom-env nodejs 模块,它允许您使用流行的.env方法为不同的阶段添加不同的环境变量。环境和环境示例.env_dev.env.stagingstaging

于 2019-03-28T09:28:12.617 回答
0

您的文件和代码正确您的 cmd 命令错误

使用这个命令

setx app_key 新密钥

于 2018-07-14T08:37:16.710 回答
0

注意力!

如果 config/production.json

{
  "key": "prod_key"
}

和 config/local.json

{
  "key": "local_key"
}

NODE_ENV=production node app.js

输出是:local_key

如果 local.json 存在是 NODE_ENV=production 被忽略

详情 S. config Wiki(很精致,可惜例子太少了)

于 2021-08-11T17:50:45.877 回答