Last active
November 15, 2023 11:32
-
-
Save davidekete/2be8b4423cda9d849d24026a1d70c106 to your computer and use it in GitHub Desktop.
A script that watches your .env file and updates your .env.example file
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 chokidar = require('chokidar'); | |
| const envFilePath = './.env'; | |
| const exampleFilePath = './.env.example'; | |
| /** | |
| * Reads the contents of the .env file and returns an array of variable names. | |
| * @returns A set of variable names from the .env file. | |
| */ | |
| const readVariablesFromEnv = () => { | |
| if (!fs.existsSync(envFilePath)) { | |
| return new Set(); | |
| } | |
| const content = fs.readFileSync(envFilePath, 'utf8'); | |
| return new Set( | |
| content | |
| .split('\n') | |
| .filter((line) => line.includes('=')) | |
| .map((line) => line.split('=')[0]), | |
| ); | |
| }; | |
| /** | |
| * Updates the .env.example file with the variable names from the .env file. | |
| */ | |
| const updateExampleFile = () => { | |
| // Read variable names from the .env file | |
| const envVars = readVariablesFromEnv(); | |
| console.log(`Updating ${exampleFilePath}`); | |
| const updatedContent = Array.from(envVars) | |
| .map((varName) => `${varName}=`) | |
| .join('\n'); | |
| fs.writeFileSync(exampleFilePath, updatedContent); | |
| }; | |
| const watcher = chokidar.watch(envFilePath, { persistent: true }); | |
| watcher.on('change', updateExampleFile); | |
| console.log(`Watching for changes in ${envFilePath}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment