Skip to content

Instantly share code, notes, and snippets.

@davidekete
Last active November 15, 2023 11:32
Show Gist options
  • Select an option

  • Save davidekete/2be8b4423cda9d849d24026a1d70c106 to your computer and use it in GitHub Desktop.

Select an option

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
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