Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are environment variables stored in node.js?

Tags:

node.js

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?

like image 403
arslan Avatar asked Jan 03 '23 08:01

arslan


2 Answers

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 
})
like image 121
Puneet Singh Avatar answered Jan 16 '23 00:01

Puneet Singh


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);
like image 24
Rohan Kumar Avatar answered Jan 16 '23 01:01

Rohan Kumar