Skip to content

Instantly share code, notes, and snippets.

@GJivan
Created March 2, 2024 16:28
Show Gist options
  • Save GJivan/c029fa061c98be100bfb13b08425c11e to your computer and use it in GitHub Desktop.
Save GJivan/c029fa061c98be100bfb13b08425c11e to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
const envFilePath = path.resolve(__dirname, '.env');
// Function to read the .env file and return its content as an array of lines
function readEnvFile() {
return fs.readFileSync(envFilePath, 'utf8').split('\n');
}
// Function to write the modified content back to the .env file
function writeEnvFile(lines) {
fs.writeFileSync(envFilePath, lines.join('\n'), 'utf8');
}
// Function to add or update a key-value pair in the .env file
function upsertEnvKey(key, value) {
const lines = readEnvFile();
let keyFound = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Skip empty lines and comments
if (line.trim() === '' || line.trim().startsWith('#')) continue;
const [currentKey] = line.split('=');
if (currentKey.trim() === key) {
lines[i] = `${key}=${value}`; // Update the existing key
keyFound = true;
break;
}
}
if (!keyFound) {
lines.push(`${key}=${value}`); // Add the new key-value pair
}
writeEnvFile(lines);
}
// Function to remove a key from the .env file
function removeEnvKey(key) {
let lines = readEnvFile();
lines = lines.filter(line => {
if (line.trim().startsWith('#') || line.trim() === '') return true; // Keep comments and empty lines
const [currentKey] = line.split('=');
return currentKey.trim() !== key;
});
writeEnvFile(lines);
}
// Example usage
upsertEnvKey('MY_KEY', 'myValue'); // Add or update MY_KEY
removeEnvKey('ANOTHER_KEY'); // Remove ANOTHER_KEY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment