简体   繁体   中英

How to save changes in .env file in node.js

I use dotenv for read environment variable. like this:

let dotenv = require('dotenv').config({ path: '../../.env' });
console.log(process.env.DB_HOST);

Now I wanna to save changes in .env file. I can't find any way to save variable in .env file. What should I do?

process.env.DB_HOST = '192.168.1.62';

.env file

VAR1=var1Value
VAR_2=var2Value

index.js file

    const fs = require('fs') 
    const envfile = require('envfile')
    const sourcePath = '.env'
    console.log(envfile.parseFileSync(sourcePath))
    let parsedFile = envfile.parseFileSync(sourcePath);
    parsedFile.NEW_VAR = 'newVariableValue'
    fs.writeFileSync('./.env', envfile.stringifySync(parsedFile)) 
    console.log(envfile.stringifySync(parsedFile))

final .env file install required modules and execute index.js file

VAR1=var1Value
VAR_2=var2Value
NEW_VAR=newVariableValue

I solve problem with envfile module:

const envfile = require('envfile');
const sourcePath = '../../.env';
let sourceObject = {};
// Parse an envfile path
// async
envfile.parseFile(sourcePath, function (err, obj) {
  //console.log(err, obj)
  sourceObject = obj;
  sourceObject.DB_HOST = '192.168.1.62';

  envfile.stringify(sourceObject, function (err, str) {
      console.log( str);
      fs.writeFile(sourcePath, str, function(err) {
          if(err) {
              return console.log(err);
          }

          console.log("The file was saved!");
       });
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM