How to read environment variables from Node.js

Understand how to read and use environment variables in Node.js programs

ThisprocessThe core module of Node providesenvThis attribute carries all environment variables set during the startup process.

This is an example of accessing the NODE_ENV environment variable, which is set todevelopmentby default.

notes:processNo need to "require", it will be available automatically.

process.env.NODE_ENV // "development"

Setting it to "production" before the script runs will tell Node that this is a production environment.

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

Here, we set 2 variables for API_KEY and API_SECRET

API_KEY=123123 API_SECRET=456456 node app.js

We can get them by running in Node.js

process.env.API_KEY // "123123"
process.env.API_SECRET // "456456"

You can write environment variables in.envFile, then

npm install dotenv

At the beginning of the main node file, add


In this way, you can avoid listing environment variables on the command line before the command line.nodeCommand, these variables will be automatically extracted.

Download mine for freeNode.js manual

More node tutorials: