You can use the fs, os module and some basic array/string operations.
const fs = require("fs"); const os = require("os"); function setEnvValue(key, value) { // read file from hdd & split if from a linebreak to a array const ENV_VARS = fs.readFileSync("./.env", "utf8").split(os.EOL); // find the env we want based on the key const target = ENV_VARS.indexOf(ENV_VARS.find((line) => { return line.match(new RegExp(key)); })); // replace the key/value with the new value ENV_VARS.splice(target, 1, `${key}=${value}`); // write everything back to the file system fs.writeFileSync("./.env", ENV_VARS.join(os.EOL)); } setEnvValue("VAR1", "ENV_1_VAL");
.env
VAR1=VAL1 VAR2=VAL2 VAR3=VAL3
Afer the executen, VAR1 will be ENV_1_VAL
No external modules no magic ;)
fsmodule to read the data and change the data and saving, so just look up how to use thefsmodule..envfile is updated you need to restart your server to use the new environment variables.