PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 20, 2022

[FIXED] How to save changes in .env file in node.js

 August 20, 2022     environment-variables, javascript, node.js     No comments   

Issue

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

Solution

.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


Answered By - Abdul Aleem
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing