Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update ENV variables in a Process without restarting it (NodeJS)?

I have a server running on NodeJS. Is there a way to update the environment variables in the process without restarting the server?

What I'm looking to do is:

  1. Start my server npm start
  2. type something into the console to update ENV variable
  3. Server restarts with new environment variable
like image 922
nikjohn Avatar asked Jul 20 '18 15:07

nikjohn


3 Answers

From a programmatic standpoint, you should be able to update the process.env variable that was passed into the running process.

For example, running:

cmd_line$: MY_VALUE=some_val node ./index.js

with code:

console.log(process.env.MY_VALUE)
process.env.MY_VALUE = 'some other value'
console.log(process.env.MY_VALUE)
process.env.MY_VALUE = 4
console.log(process.env.MY_VALUE)

output in terminal:

some_val
some other value
4

From a server admin standpoint for an already running application, I don't know the answer to that.

like image 125
jsadler Avatar answered Oct 22 '22 07:10

jsadler


It's possible to debug Node.js process and change global variables:

debug

On *nix, it's possible to enable debugging even if a process wasn't started in debug mode. On Windows, it's possible to debug only processes that were started with node --inspect. This article explains both possibilities in detail.

Obviously, this will work only if environment variables are used directly all the time as process.env.FOO.

If their values are initially used, changing process.env.FOO later may not affect anything:

const FOO = process.env.FOO;
...
console.log(FOO); // it doesn't matter whether process.env.FOO was changed at this point
like image 43
Estus Flask Avatar answered Oct 22 '22 05:10

Estus Flask


If you make a change to env variables they will take place immediately only if you make the change via the main Properties dialog for the system which is going to my computer -> Advanced properties -> Environment Variables.

Any program which is already running will not see the changes unless we handle it in the code explicitly.

Logic behind it is that there is an agent which sends a broadcasting a WM_SETTINGCHANGE message and make changes to all applications inorder to notify for that change.

like image 29
LearningToCode Avatar answered Oct 22 '22 05:10

LearningToCode