Skip to content

Instantly share code, notes, and snippets.

@sjmeverett
Created August 18, 2020 16:28
Show Gist options
  • Select an option

  • Save sjmeverett/deee09bff25b38ff9cf02b2d058bd7fc to your computer and use it in GitHub Desktop.

Select an option

Save sjmeverett/deee09bff25b38ff9cf02b2d058bd7fc to your computer and use it in GitHub Desktop.
const { promises: fs } = require('fs');
const path = require('path');
main(process.argv.slice(2)).catch(console.error);
async function main(argv) {
if (argv.length !== 3) {
printUsage();
process.exit(1);
}
switch (argv[0]) {
case 'export':
await exportEnv(argv[1], argv[2]);
break;
case 'import':
await importEnv(argv[1], argv[2]);
break;
default:
printUsage();
process.exit(1);
}
}
function printUsage() {
console.log('Usage: dotenv <import|export> <input dir> <output dir>');
}
async function exportEnv(inputDir, outputDir) {
const dirs = await getDirs(inputDir);
await fs.mkdir(outputDir, { recursive: true });
for (const dir of dirs) {
try {
await fs.copyFile(
path.join(inputDir, dir, '.env'),
path.join(outputDir, dir + '.env'),
);
} catch (err) {
console.error(err.message);
}
}
}
async function importEnv(inputDir, outputDir) {
const envs = await getDotEnvs(inputDir);
for (const env of envs) {
try {
await fs.copyFile(
path.join(inputDir, env),
path.join(outputDir, path.basename(env, '.env'), '.env'),
);
} catch (err) {
console.error(err.message);
}
}
}
async function getDotEnvs(dir) {
const files = await fs.readdir(dir, { withFileTypes: true });
return files
.filter((file) => file.isFile() && file.name.endsWith('.env'))
.map((file) => file.name);
}
async function getDirs(dir) {
const files = await fs.readdir(dir, { withFileTypes: true });
return files.filter((file) => file.isDirectory()).map((file) => file.name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment