简体   繁体   English

NodeJs环境变量vs配置文件

[英]NodeJs Environment variables vs config file

Actually I have a nodejs express app with its config file for params like host, port, JWT token, DB params and more. 实际上我有一个nodejs express app及其配置文件,用于主机,端口,JWT令牌,DB参数等等。

The question is if it could have sense to keep those params directly on environment variables (whitout any config file) and acces them without the need of do the "require" for config in all components and modules. 问题是,如果将这些参数直接保存在环境变量上(对任何配置文件进行输出)并且无需在所有组件和模块中对“配置”进行“需求”即可访问它们。

All examples I see uses a config file, probably something about security or memory? 我看到的所有示例都使用配置文件,可能是关于安全性或内存的?

Another possibility is using an .env files in nodejs. 另一种可能性是在nodejs中使用.env文件。 I think you have to npm install dotenv in your application. 我想你必须在你的应用程序中安装dotenv Ideally different instances (dev, prod....) have its own .env file, and you dont have to call require("dotenv") every time if you want to access the environment variable. 理想情况下,不同的实例(dev,prod ....)有自己的.env文件,如果要访问环境变量,每次都不必调用require(“dotenv”) Call it in the very beginning ie) in app.js and you can access the environment variable in any of the sub-files. 在app.js的最开始调用它,你可以在任何子文件中访问环境变量。

A config file lets your very quickly set the entire environment of a machine - eg S3 buckets, API urls, access keys, etc. If you separate these into separate process.env.VARIABLE then you would need to set each of these...for which you would likely make a script...and now you have an environment file again! 配置文件可以让您快速设置机器的整个环境 - 例如S3存储桶,API网址,访问密钥等。如果您将它们分成单独的process.env.VARIABLE那么您需要设置其中的每一个......你可能会制作一个脚本......现在你又有了一个环境文件!

To access environment variables you can use process.env.VARIABLE in your nodejs code (is always a string), as long as the variable is set before the process is started. 要访问环境变量,只要在启动进程之前设置变量,就可以在nodejs代码中使用process.env.VARIABLE (始终为字符串)。

config file is usually for setting the default values for your environment variables, 配置文件通常用于设置环境变量的默认值,

which is needed when you are writing the test cases and need to use default values or mock values, 在编写测试用例时需要使用默认值或模拟值,

and also you will have all the env variables at one place which is better management. 并且你将在一个地方拥有所有env变量,这是更好的管理。

so if you have an environment variable x, 所以如果你有一个环境变量x,

in config file you can keep it as 在配置文件中,您可以将其保留为

config.x = process.env.x || config.x = process.env.x || 'defaultVale or mockValue' 'defaultVale或mockValue'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM