Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update attributes in .env file in Node JS

I am wrting a plain .env file as following:

VAR1=VAL1
VAR2=VAL2

I wonder if there's some module I can use in NodeJS to have some effect like :

somefunction(envfile.VAR1) = VAL3

and the resulted .env file would be

VAR1=VAL3
VAR2=VAL2

i.e., with other variables unchanged, just update the selected variable.

like image 934
IsaIkari Avatar asked May 06 '26 06:05

IsaIkari


1 Answers

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 ;)

like image 190
Marc Avatar answered May 08 '26 21:05

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!