简体   繁体   中英

nodejs .env variable undefined

I am getting undefined when trying to get the value from .env

Here is my server.js

 console.log(process.env.val);

Here is my .env file

 val=hello

Screenshot that shows the file hierarchy

When I run the server I get undefined. How to fix?

You need to use dotenv library

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE . For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM