Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shreekrishnalamichhane/6a21ef1c307aa9ee4b8f6fbbe086e067 to your computer and use it in GitHub Desktop.
Save shreekrishnalamichhane/6a21ef1c307aa9ee4b8f6fbbe086e067 to your computer and use it in GitHub Desktop.
Generate env diff between two files
const fs = require("fs");
// Function to read the .env file and parse it into a key-value object
function readEnvFile(filePath) {
const envData = {};
const fileContent = fs.readFileSync(filePath, "utf-8");
fileContent.split("\n").forEach((line) => {
const trimmedLine = line.trim();
// Ignore empty lines and comments
if (trimmedLine === "" || trimmedLine.startsWith("#")) {
return;
}
// Split the line into key and value at the first '='
const [key, ...valueParts] = trimmedLine.split("=");
const value = valueParts.join("=").trim();
if (key) {
envData[key.trim()] = value || "";
}
});
return envData;
}
// Function to compare two .env files
function compareEnvFiles(file1, file2) {
const env1 = readEnvFile(file1);
const env2 = readEnvFile(file2);
const allKeys = new Set([...Object.keys(env1), ...Object.keys(env2)]);
const resultTable = [];
let serialNo = 1;
console.log(`Comparing ${file1} and ${file2}:\n`);
// Iterate through all unique keys from both files
allKeys.forEach((key) => {
const inExample = env2[key] !== undefined ? "Set" : "Not Set";
const inLocal = env1[key] !== undefined ? "Set" : "Not Set";
resultTable.push({
"S/No": serialNo++,
"Key Name": key,
"In Example": inExample,
"In Local": inLocal,
});
});
// Output the result in table format
console.table(resultTable);
// Output detailed value differences for keys that exist in both files but have different values
console.log("Detailed Value Differences:");
allKeys.forEach((key) => {
if (env1[key] !== env2[key]) {
console.log("---------------------------------------");
console.log(`Key: ${key}`);
console.log(`In Example: ${env2[key] || "Not Set"}`);
console.log(`In Local: ${env1[key] || "Not Set"}`);
}
});
}
// Example usage
const file1 = ".env.local";
const file2 = ".env.example";
compareEnvFiles(file1, file2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment