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.
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.
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.
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.
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.
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.
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.
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