Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javascript: Function to compare different .env files
/*
* Created: 14/1/2022 by Jakub Zomerfeld / dev.zomerfeld@gmail.com
*/
const fs = require('fs')
const path = require('path')
const dotenv = require('dotenv')
/**
*
* // IFFE Function to check existing env files and compare their keys and validate
*/
;(() => {
const envExt = '.env'
const envConfigFile = `${envExt}.config`
const envsToCompareWithConfig = [`${envExt}`]
const envFilesArray = envsToCompareWithConfig.map(
(item, index) => envsToCompareWithConfig[index]
)
const parsedEnvFiles = envFilesArray.map(envFileName =>
parseFile(envFileName)
)
if (
!compareEnvKeyArrays(
returnEnvKeys(parseFile(envConfigFile)),
...parsedEnvFiles.map((item, index) =>
returnEnvKeys(parsedEnvFiles[index])
)
)
) {
throw new Error(
`There is a mismatch between: (${Object.values(
envFilesArray
)}) env files, compare existing variables.`
)
}
console.log(
`%cDEBUG: Env are identical between ${envConfigFile} and other: [${Object.values(
envFilesArray
)}] files`,
'color: green; background: white;'
)
})()
/**
*
* //Function to read file and parse it by 'dotenv' by fileName
* @param {string} fileName
* @return {File}
*/
function parseFile(fileName) {
return dotenv.parse(fs.readFileSync(path.resolve('./', fileName)))
}
/**
* //Function to compare arrays of env keys
*
* @param {array:keys} configEnvArray
* @param {array} args array of different .env files keys
* @return {boolean}
*/
function compareEnvKeyArrays(configEnvArray, ...args) {
const booleanArray = args.map((item, index) => {
const compare = JSON.stringify(configEnvArray) === JSON.stringify(item)
if (!compare) {
const difference = returnArraysDifference(configEnvArray, item)
console.warn(
`Mismatch between .env.config & array provided on index [${index}]. Difference: [${difference}]`
)
}
return compare
})
return booleanArray.every(value => value)
}
/**
*
* //Function to get array of keys from env
* @param {File} envFile
* @return {array}
*/
function returnEnvKeys(envFile) {
return Object.keys(envFile)
}
/**
*
* //Function to get difference between two arrays
* @param {array} firstArray
* @param {array} secondArray
* @return {array}
*/
function returnArraysDifference(firstArray, secondArray) {
return firstArray.filter(x => !secondArray.includes(x))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment