Is there a way I can read environment variables in Node.js code?
是否有一种方法可以在节点中读取环境变量。js代码?
Like for example Python's os.environ['HOME']
.
比如Python的os.environment(“HOME”)。
4 个解决方案
#1
1499
process.env.ENV_VARIABLE
Where ENV_VARIABLE
is the name of the variable you wish to access.
其中ENV_VARIABLE是您希望访问的变量的名称。
See Node.js docs for process.env
.
看到节点。js process.env文档。
#2
100
When using Node.js, you can retrieve environment variables by key from the process.env
object:
当使用节点。js,您可以通过关键的过程来检索环境变量。env对象:
for example
例如
var mode = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'
Here is the answer that will explain setting environment variables in node.js
下面是在node.js中解释设置环境变量的答案。
#3
40
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use process.env[v]
.
如果您想使用在节点中生成的字符串键。js程序,比如var v = 'HOME',你可以使用process.env[v]。
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
否则,process.env。VARNAME必须硬编码在您的程序中。
#4
3
You can use env package to manage your environment variables per project:
您可以使用env包来管理每个项目的环境变量:
- Create a
.env
file under the project directory and put all of your variables there. - 在项目目录下创建一个.env文件并将所有的变量放在那里。
- Add this line in the top of your application entry file:
require('dotenv').config();
- 在应用程序条目文件的顶部添加这一行:require(“dotenv”).config();
Done. Now you can access your environment variables with process.env.ENV_NAME
.
完成了。现在,您可以使用process.env.ENV_NAME访问环境变量。
#1
1499
process.env.ENV_VARIABLE
Where ENV_VARIABLE
is the name of the variable you wish to access.
其中ENV_VARIABLE是您希望访问的变量的名称。
See Node.js docs for process.env
.
看到节点。js process.env文档。
#2
100
When using Node.js, you can retrieve environment variables by key from the process.env
object:
当使用节点。js,您可以通过关键的过程来检索环境变量。env对象:
for example
例如
var mode = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'
Here is the answer that will explain setting environment variables in node.js
下面是在node.js中解释设置环境变量的答案。
#3
40
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use process.env[v]
.
如果您想使用在节点中生成的字符串键。js程序,比如var v = 'HOME',你可以使用process.env[v]。
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
否则,process.env。VARNAME必须硬编码在您的程序中。
#4
3
You can use env package to manage your environment variables per project:
您可以使用env包来管理每个项目的环境变量:
- Create a
.env
file under the project directory and put all of your variables there. - 在项目目录下创建一个.env文件并将所有的变量放在那里。
- Add this line in the top of your application entry file:
require('dotenv').config();
- 在应用程序条目文件的顶部添加这一行:require(“dotenv”).config();
Done. Now you can access your environment variables with process.env.ENV_NAME
.
完成了。现在,您可以使用process.env.ENV_NAME访问环境变量。