I don't quite get what you are trying to do, but usually environment variables are set for runtime. You shouldn't update env variables when your app is running.
For dotenv (https://www.npmjs.com/package/dotenv), you create a file .env
put some variables there:
FOO=bar
BAZ=bob
Then require and use your .env file
require('dotenv').config();
console.log(process.env.FOO);
// bar
Without any libraries you can also provide env variables directly to node script like this
USER_ID=abc USER_PASSWORD=def node app.js
And again use it like:
console.log(process.env.USER_ID);
// abc
You should not include the .env
in your version control repository (add it to your .gitignore
file).
In JavaScript you can use either environment variable, or if it is not defined, add something else for example:
const yourVariable = process.env.yourVariable || 'Get stuff done';
If the process.env.yourVariable is not defined the app will use "Get stuff done" string instead.
And what I think you are asking for is something that I bet you shouldn't do with env variables. Anyways this is a hack I found, and probably should work. You can set new env variable on runtime like this (I have not tried) as environment variables are intended to be set from the outside of the code, not inside. However there might be use cases where you want to use this, launching child processes or tests or what ever.
process.env['NODE_ENV'] = 'production';
If you want to write the values in .env during runtime, you need to read and append to the file which is whole new story. Good luck.
.env
file?