(node.js) 如何在 JSON 文件中使用环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36962601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:10:08  来源:igfitidea点击:

(node.js) how to use environment variables in JSON file

node.js

提问by Ben

I'm using a 3rd party library that needs a JSON config file, and I need to pass some env variables in as key values. If I include them as I normally would, eg:

我正在使用需要 JSON 配置文件的 3rd 方库,并且需要将一些 env 变量作为键值传入。如果我像往常一样包含它们,例如:

  "s3": {
    "key": process.env.AWS_ACCESS_KEY_ID,
    "secret": process.env.AWS_SECRET_ACCESS_KEY,
    "bucket": process.env.S3_MLL_BUCKET_NAME,
    "destination": "/backups/database",
    "encrypt": false,
    "region": process.env.AWS_REGION
  }

...I get the error:

...我收到错误:

SyntaxError: config/s3_backup.config.json: Unexpected token p

回答by dtoux

JSON does not have notion of environment variables. What you can do though is to declare your configuration file as node.jsmodule and then you will be able to use your environment variables as follows:

JSON 没有环境变量的概念。您可以做的是将您的配置文件声明为node.js模块,然后您将能够使用您的环境变量,如下所示:

module.exports = {
  s3: {
    key: process.env.AWS_ACCESS_KEY_ID,
    secret: process.env.AWS_SECRET_ACCESS_KEY,
    bucket: process.env.S3_MLL_BUCKET_NAME,
    destination: "/backups/database",
    encrypt: false,
    region: process.env.AWS_REGION
  }
};

回答by Muganwas

I had the same issue, what worked for me was using a js file and exporting an object module.exports = {config: {"exampleAPIKey":"ruier4343"}}...then "stringifying" the object and then parsing it back to json const config = require("./jsConfigs.js").config; const jsonConfig = JSON.parse(JSON.stringify(config))I had tried it so many different ways but this is the only one that worked.

我遇到了同样的问题,对我有用的是使用 js 文件并导出一个对象module.exports = {config: {"exampleAPIKey":"ruier4343"}}……然后“字符串化”对象,然后将其解析回 jsonconst config = require("./jsConfigs.js").config; const jsonConfig = JSON.parse(JSON.stringify(config))我已经尝试了很多不同的方法,但这是唯一一种工作。