Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set process.env from the file in NodeJS?

I'm new to the Node.JS. I found few articles says we can use .env file to setup the process.env variable, e.g.,

PORT = 8081

but when I run the program in my node, it is still 8080 PORT (by default). The question is how can I setup the env variable in Node without any other 3rd party module's help? (I found there are few 3rd party package to management the env config, but... it is kind confused, different package might have different rule and more complex use cases; I want to start from clear way to study purely nodejs)

Update

I have read Node Environment Setting post on StackOverFlow, but they are refer using 3rd party package, none of them tells the detail steps. (Either windows system environment, or Linux environment variables... but how can I place the setting into my project folder?!)

like image 434
Weijing Lin Avatar asked Feb 22 '17 07:02

Weijing Lin


People also ask

What is .env file in Nodejs?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables. The dotenv library reads this.


2 Answers

Dotenv file have become the most popular mode to separate configuratione from app, using system environment variables (see 12factor config).

On node there exists a lot of libraries for loading config from .env file. The most popular is motdotla/dotenv. You can read a lot of examples on readme file about the usage of this library

like image 145
Giorgio Cerruti Avatar answered Nov 15 '22 09:11

Giorgio Cerruti


Make a config.js file with the following content:

module.exports = {
    bar: 'someValue',
    foo: 'otherValue'
    ...
}

Then you can do this in some file:

const config = require('./config');
let foo = config.foo;
like image 32
jesusgn90 Avatar answered Nov 15 '22 10:11

jesusgn90