如何从 Node.js 读取环境变量
¥How to read environment variables from Node.js
Node.js 的 process 核心模块提供了 env 属性,该属性托管在启动进程时设置的所有环境变量。
¥The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.
以下代码运行 app.js 并设置 USER_ID 和 USER_KEY。
¥The below code runs app.js and set USER_ID and USER_KEY.
USER_ID=239482 USER_KEY=foobar node app.js
这将把用户 USER_ID 作为 239482 传递,把 USER_KEY 作为 foobar 传递。这适用于测试,但对于生产,你可能需要配置一些 bash 脚本来导出变量。
¥That will pass the user USER_ID as 239482 and the USER_KEY as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.
注意:
process不需要导入,它是 Node.js 中的全局对象。¥Note:
processdoes not need to be imported, it is a global object in Node.js.
以下是访问我们在上述代码中设置的 USER_ID 和 USER_KEY 环境变量的示例。
¥Here is an example that accesses the USER_ID and USER_KEY environment variables, which we set in above code.
console.log(process.env.USER_ID); // "239482"
console.log(process.env.USER_KEY); // "foobar"
以同样的方式,你可以访问你设置的任何自定义环境变量。
¥In the same way you can access any custom environment variable you set.
Node.js 20 引入了实验性的 对 .env 文件的支持。
¥Node.js 20 introduced experimental support for .env files.
现在,你可以在运行 Node.js 应用时使用 --env-file 标志指定环境文件。以下是示例 .env 文件以及如何使用 process.env 访问其变量。
¥Now, you can use the --env-file flag to specify an environment file when running your Node.js application. Here's an example .env file and how to access its variables using process.env.
# .env file
PORT=3000
在你的 js 文件中
¥In your js file
console.log(process.env.PORT); // "3000"
运行 app.js 文件,并在 .env 文件中设置环境变量。
¥Run app.js file with environment variables set in .env file.
node --env-file=.env app.js
此命令从 .env 文件加载所有环境变量,使它们可用于 process.env 上的应用
¥This command loads all the environment variables from the .env file, making them available to the application on process.env
此外,你可以传递多个 --env-file 参数。后续文件将覆盖先前文件中定义的预先存在的变量。
¥Also, you can pass multiple --env-file arguments. Subsequent files override pre-existing variables defined in previous files.
node --env-file=.env --env-file=.development.env app.js
注意:如果在环境和文件中定义了相同的变量,则环境中的值优先。
¥Note: if the same variable is defined in the environment and in the file, the value from the environment takes precedence.
如果你想选择性地从 .env 文件中读取,可以使用 --env-file-if-exists 标志避免在文件丢失时抛出错误。
¥In case you want to optionally read from a .env file, it's possible to avoid
throwing an error if the file is missing using the --env-file-if-exists flag.
node --env-file-if-exists=.env app.js