Skip to content

Instantly share code, notes, and snippets.

@johannschopplich
Created April 24, 2024 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johannschopplich/27225ae1851d8a448790f655c0c375d4 to your computer and use it in GitHub Desktop.
Save johannschopplich/27225ae1851d8a448790f655c0c375d4 to your computer and use it in GitHub Desktop.
Backup all your .env files while keeping the directory structure of the source directory
import process from "node:process";
import fsp from "node:fs/promises";
import path from "node:path";
import fg from "fast-glob";
async function copyEnvFiles(sourceDir, backupDir) {
try {
const envFiles = await fg(["**/.env"], {
cwd: sourceDir,
ignore: ["**/node_modules/**"],
});
for (const envFile of envFiles) {
const sourcePath = path.join(sourceDir, envFile);
const targetPath = path.join(backupDir, envFile);
// Create the backup directory if it doesn't exist
await fsp.mkdir(path.dirname(targetPath), { recursive: true });
// Copy the .env file
await fsp.copyFile(sourcePath, targetPath);
console.log(`Copied ${envFile} to ${targetPath}`);
}
} catch (error) {
console.error("Error during backup:", error.message);
}
}
const sourceDirectory = process.argv[2];
const backupDirectory = process.argv[3];
if (!sourceDirectory || !backupDirectory) {
console.error(
"Usage: node backup-env-files.mjs <source-directory> <backup-directory>"
);
process.exit(1);
}
await copyEnvFiles(sourceDirectory, backupDirectory);
console.log("Backup completed successfully!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment