I want to add some variables to environment variables, but could not find the file which stores these variables.
I checked package.JSon and every folders, but can't find the file storing them.
Where does node.js store it's environment variables?
You can create a .env
file in your application folder and define all the environment variables you want to use in the application. Below are sample contents of such a file.
DB_HOST=localhost
DB_USER=root
DB_PASS=123456
Then use the dotenv npm package to import all the variables from the .env
file to the node process environment. Then you can access those variables from the process.env
object.
require('dotenv').config()
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
As pointed in the comments, you have to provide these variables while invoking your node program:
$ NODE_ENV=test node yourApp.js
And you can access this in your code as:
console.log("Environment variable: " + process.env.NODE_ENV);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With