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

14,071

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
14,071

Related videos on Youtube

nikjohn
Author by

nikjohn

Updated on June 04, 2022

Comments

  • nikjohn
    nikjohn almost 2 years

    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
  • nikjohn
    nikjohn over 5 years
    This is kind of what I want, but I am looking to see if there is a way to do this on the console directly