首页 > 解决方案 > Is there a way to load a .json configuration file and automatically substitute environment variables?

问题描述

I'm a little new to the javascript ecosystem, so apologies if I'm asking the question wrong.

I'm working on a legacy project that loads configuration files from .json files. In those .json files there are variables that need to be substituted with environment variables.

For example config.json:

{
  "database": {
    "host": "%DBHOST%",
    "port": "%DBPORT%"
  }
}

In the legacy code, there are complicated startup scripts that use sed to do variable substitution. I'm moving the project into docker and would much rather define DBHOST/DBPORT etc in the docker definitions and have it magically update the configuration. Right now, I just have docker running a script that does the sed operation which works, but this feels clunky. Is there a way I can tell node to load the .json file and automatically substitute the %VAR% blocks with an environment variable if there is a match?

标签: javascriptnode.jsjsonnpmdocker-compose

解决方案


使用 NodeJS,您可以像这样加载环境变量:

process.env.VARIABLE_NAME

推荐阅读