Created
November 5, 2019 00:21
-
-
Save sajadtorkamani/e5275e22da283dcd7fa348ee81901d52 to your computer and use it in GitHub Desktop.
Redundant node script to check envvars are set correctly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const dotenv = require('dotenv'); | |
const chalk = require('chalk'); | |
/** | |
* Parse env file into object. | |
* | |
* @param {string} path - Absolute path to env file. | |
* @returns {object} - Object containing all env vars from file. | |
*/ | |
const parseFile = path => { | |
const content = fs.readFileSync(path); | |
return dotenv.parse(content); | |
}; | |
/** | |
* Check that all envvars are defined. | |
* | |
* @param {string} reference - The absolute path to the reference env file. | |
* @param {string} actual - The absolute path to the actual env file. | |
*/ | |
const checkEnvvars = (reference, actual) => { | |
// Throw if .env doesn't exist | |
if (!fs.existsSync(actual)) { | |
console.log(chalk.red(`${actual} does not exist`)); | |
process.exit(1); | |
} | |
const requiredVars = Object.keys(parseFile(reference)); | |
const actualVars = parseFile(actual); | |
const missingVars = requiredVars.filter(varName => !actualVars[varName]); | |
if (missingVars.length > 0) { | |
console.log( | |
chalk.red( | |
`Missing the following vars in ${path.basename(actual)}: ${missingVars}` | |
) | |
); | |
process.exit(1); | |
} | |
}; | |
checkEnvvars( | |
path.join(__dirname, '..', '.env.sample'), | |
path.join(__dirname, '..', '.env') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment