Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set an environmental variable in node.js?

Tags:

node.js

How can I set an environmental variable in node.js?

I would prefer not to rely on anything platform specific, such as running export or cmd.exe's set.

like image 800
abrkn Avatar asked May 31 '12 07:05

abrkn


People also ask

Do I need to set environment variable for node?

You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.

How do I set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How do I manage environment variables in node js?

If you have multiple environment variables in your node project, you can also create an . env file in the root directory of your project, and then use the dotenv package to load them during runtime. You can also run your js file with node -r dotenv/config index.

How do you set environment as production in node js?

You can signal Node. js that you are running in production by setting the NODE_ENV=production environment variable. in the shell, but it's better to put it in your shell configuration file (e.g. . bash_profile with the Bash shell) because otherwise the setting does not persist in case of a system restart.


2 Answers

You can set your environment variables in process.env:

process.env['VARIABLE'] = 'value'; 

-OR-

process.env.VARIABLE = 'value'; 

Node should take care of the platform specifics.

like image 90
lanzz Avatar answered Oct 25 '22 09:10

lanzz


First you should install this package :- https://github.com/motdotla/dotenv [npm install dotenv]

Then you need to create a .env file in your project's root directory, and there you can add variables like below:-

NODE_ENV=PRODUCTION DATABASE_HOST=localhost 

Now you can easily access these variables in your code like below:-

require('dotenv').config() console.log(process.env.NODE_ENV); 

It worked for me, hopefully that helps.

like image 37
jagjeet Avatar answered Oct 25 '22 10:10

jagjeet