0

How to read and write env files?

Original file:

# I am a note ... key1=value1 key2=value2 # I am a note ... 

I need a function setEnv(key, value).

run setEnv('key1', 'value2'), Let it become:

# I am a note ... key1=value2 key2=value2 # I am a note ... 

How can I achieve it?

1
  • all you need to do is literally split each line on the first = 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 Commented Dec 11, 2020 at 13:03

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the envfile module as described here.

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

2 Comments

but It does not output # note
That's due to the module parsing only the actual key-value-pairs. You could manually parse each line, but that seems very error prone. Do you need to set comments programmatically as well?
0

Something like this:

function setEnv(envText, key, value) { if (!envText) { return; } const rp = new RegExp(`${key}=(.*?)\\s`); let result = envText.replace(rp, (m, $1) => { return m.replace($1, value); }); if (!rp.test(result)) { result += `\n${key}=${value}`; } return result; } console.log( setEnv( `# I am a note ... key1=value1 key2=value2 # I am a note ...`, 'key1', 'value2', ), );

But this doesn't work:

setEnv( `# I am a note ... key1=value1 key2=value2`, 'key2', 'value1', ) 
setEnv( `# I am a note ... key1key2=value1 key2=value2`, 'key2', '2222', ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.