Skip to main content

如何访问和转换环境变量

¥How to access and cast environment variables

在大多数用例中,环境之间会有不同的配置(例如数据库凭据)。

¥In most use cases there will be different configurations between environments (e.g. database credentials).

可以在应用根目录的 .env 文件中定义变量,而不是将这些凭据写入配置文件:

¥Instead of writing those credentials into configuration files, variables can be defined in a .env file at the root of the application:

# path: .env

DATABASE_PASSWORD=acme

要自定义要加载的 .env 文件的路径,请在启动应用之前设置一个名为 ENV_PATH 的环境变量:

¥To customize the path of the .env file to load, set an environment variable called ENV_PATH before starting the application:

ENV_PATH=/absolute/path/to/.env npm run start

访问环境变量

¥Accessing environment variables

可以在配置和应用文件中的任何位置使用 process.env.{variableName} 访问 .env 文件中定义的变量。

¥Variables defined in the .env file are accessible using process.env.{variableName} anywhere in configuration and application files.

在配置文件中,env() 实用程序允许定义默认值和 铸造值

¥In configuration files, a env() utility allows defining defaults and casting values:

./config/database.js

module.exports = ({ env }) => ({
connections: {
default: {
settings: {
password: env('DATABASE_PASSWORD'),
},
},
},
});
注意

语法 property-name: env('VAR', 'default-value') 使用存储在 .env 文件中的值。如果 .env 文件中没有指定值,则使用默认值。

¥The syntax property-name: env('VAR', 'default-value') uses the value stored in the .env file. If there is no specified value in the .env file the default value is used.

铸造环境变量

¥Casting environment variables

env() 实用程序可用于将环境变量转换为不同类型:

¥The env() utility can be used to cast environment variables to different types:

// Returns the env if defined without casting it
env('VAR', 'default');

// Cast to integer (using parseInt)
env.int('VAR', 0);

// Cast to float (using parseFloat)
env.float('VAR', 3.14);

// Cast to boolean (check if the value is equal to 'true')
env.bool('VAR', true);

// Cast to JS object (using JSON.parse)
env.json('VAR', { key: 'value' });

// Cast to array (syntax: ENV_VAR=[value1, value2, value3] | ENV_VAR=["value1", "value2", "value3"])
env.array('VAR', [1, 2, 3]);

// Cast to date (using new Date(value))
env.date('VAR', new Date());

// Returns the env matching oneOf union types
env.oneOf('UPLOAD_PROVIDER', ['local', 'aws'], 'local')