如何从 Node.js 读取环境变量

文章作者

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.

The below code runs app.js and set USER_ID and USER_KEY.

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.

Note: process does not require a "require", it's automatically available.

Here is an example that accesses the USER_ID and USER_KEY environment variables, which we set in above code.

JS

In the same way you can access any custom environment variable you set.

If you have multiple environment variables in your node project, you can also create an .env file in the root directory of your project, and then use the dotenv package to load them during runtime.

BASH

In your js file

JS

You can also run your js file with node -r dotenv/config index.js command if you don't want to import the package in your code.