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

你离开我真会死。 提交于 2021-01-19 03:41:22

问题


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

回答1:


.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



回答2:


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!");
       });
   });
});


来源:https://stackoverflow.com/questions/53360535/how-to-save-changes-in-env-file-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!