Lets start by creating new project.
mkdir folder_name cd folder_name npm init
Then in your project directory install 'envfile' and 'dotenv'. Command for installing envfile is
npm install envfile --save
Similarly install dotenv
npm install dotenv --save
package dotenv directly reads .env file package envfile is used to parse and stringify the file as required. Create .env file in the project directory with your details.
# I am a note ... key1=value1 key2=value2 # I am a note ...
Create a new file with filename.js
After that for getting and setting env variables you can use following code.
const fs = require('fs'); require('dotenv').config() const { parse, stringify } = require('envfile'); const pathToenvFile = '.env'; /** * * @param {string} key * //Function to get value from env */ function getEnv(key) { console.log("Getting value of " + key); console.log(process.env[key]); } //Calling the function getEnv getEnv("key1"); /** * * @param {string} key * @param {string} value * //Function to set environment variables. */ function setEnv(key, value) { fs.readFile(pathToenvFile, 'utf8', function (err, data) { if (err) { return console.log(err); } var result = parse(data); result[key] = value; console.log(result); fs.writeFile(pathToenvFile, stringify(result), function (err) { if (err) { return console.log(err); } console.log("File Saved"); // Can be commented or deleted }) }); } //Calling the function setEnv setEnv('key1', 'value2');
After this run your file using
node filename.js
You can get your desired output.
Initial .env file
# I am a note ... key1=value1 key2=value2 # I am a note ...
After running program
key1=value2 key2=value2
Yes your comments gets deleted.
=and write the raw value to it. there is no such thing as escaping in .env files. i see no reason in editing the files with node tho. for reading i usually use npmjs.com/package/dotenv