问题
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:
- Start my server
npm start
type something into the console to update ENV variable
- Server restarts with new environment variable
回答1:
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.
回答2:
It's possible to debug Node.js process and change global variables:
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
回答3:
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.
回答4:
Here's a good explanation on how to setup environment variables in mac OS. Additionally, as others have already answered, you can set them with process.env.ANY_VARIABLE = 'some value'
.
回答5:
I am trying to find a cross-platform answer to this (mac, linux, windows)
For mac, a workaround that I found is using
const shell = require("shelljs");
console.log(shell.exec('launchctl getenv TEST'));
It only works if you set environment variable (e.g. in other terminal tab) using launchctl setenv TEST blahblah
来源:https://stackoverflow.com/questions/51446149/how-to-update-env-variables-in-a-process-without-restarting-it-nodejs