5

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?

2
  • Environment variables aren't usually stored in a file. You set them via your shell (e.g. bash). Commented Oct 10, 2017 at 7:23
  • 1
    Environment variables are stored in your system shell that you start node.js from. They are a shell feature that node.js can read/modify. I'd suggest reading this: Working with Environment Variables in node.js. Commented Oct 10, 2017 at 7:24

3 Answers 3

7

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 
})
Sign up to request clarification or add additional context in comments.

Comments

5

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);

Comments

0

You can use a package called cross-env . https://www.npmjs.com/package/cross-env The issue with using $ NODE_ENV=test node yourApp.js is that this wont work in windows systems.

In order to use cross-env you can do the following

npm install --save-dev cross-env

Add the following to your package.json

{
  "scripts": {
      "dev": "cross-env NODE_ENV=development node index.js"
   }
}

You can run your code by running

npm run dev

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.