如何获取Object类型的环境变量?

时间:2017-08-14 12:56:44

标签: node.js express configuration environment-variables

目前我在nodejs应用程序中以这种方式设置了环境变量:

`

if (process.env.NODE_ENV === 'development') {
  process.env.LOGGER_LEVEL = 'silly';
  process.env.DB = 'db-v2-staging';
  process.env.DB_URI = 'localhost';
  process.env.SOME_FLAG = true;
  process.env.SOME_API_KEY = 'y43e6fgccdxfgvH4JR-KiUWkIvJeWiw';
  process.env.SftpServer = {
    host: '111.11.11.11',
    port: 22,
    username: 'johndoe',
    password: 'johndoe',
    input: './input_clone_test',
    output: './output_clone_test',
  };
} else if (process.env.NODE_ENV === 'production') {
  process.env.LOGGER_LEVEL = 'silly';
  process.env.DB = 'db-v2-staging';
  process.env.DB_URI = 'localhost';
  process.env.SOME_FLAG = true;
  process.env.SOME_API_KEY = 'y43e6fgccdxfgvH4JR-KiUWkIvJeWiw';
  process.env.SftpServer = {
    host: '111.11.11.11',
    port: 22,
    username: 'johndoe',
    password: 'johndoe',
    input: './input_test',
    output: './output_test',
  };
}

Problem i face is when i try to access process.env.SftpServer it gives me **"[object Object]"** as output, even if i go with JSON.stringify(process.env.SftpServer)`它给了我"" [object Object]&#34 ;" 。需要弄清楚解决方案,如果可能的话,请建议解决方案,而不使用第三方模块进行环境变量管理。

1 个答案:

答案 0 :(得分:1)

ENV变量是OS依赖的东西。它们不支持JS Object Notation。 解决方案将其设置为字符串,然后在获取时执行JSON解析。

process.env.SftpServer  = `{
  "host": "111.11.11.11",
  "port": 22, "username": "johndoe", 
  "password": "johndoe", 
  "input": "./input_clone_test", 
  "output": "./output_clone_test"
}`;


console.log(JSON.parse(process.env.SftpServer ))