editEnvVariable.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export default async (key, newValue) => {
  2. const envFile = Bun.file(`.env`);
  3. let content = "";
  4. // 1. Read existing file if it exists
  5. if (await envFile.exists()) {
  6. content = await envFile.text();
  7. }
  8. const lines = content.split("\n");
  9. let keyFound = false;
  10. // Format the value: wrap in quotes if it contains spaces
  11. const safeValue = newValue.includes(" ") ? `"${newValue}"` : newValue;
  12. // 2. Scan lines to find and replace the key
  13. for (let i = 0; i < lines.length; i++) {
  14. const line = lines[i];
  15. // Regex matches the key at the start of the line (ignoring leading spaces)
  16. const keyRegex = new RegExp(`^\\s*${key}\\s*=`);
  17. if (keyRegex.test(line)) {
  18. lines[i] = `${key}=${safeValue}`;
  19. keyFound = true;
  20. break;
  21. }
  22. }
  23. // 3. If the key wasn't found, append it to the end
  24. if (!keyFound) {
  25. // Prevent appending to the same line if the file didn't end with a newline
  26. if (lines.length > 0 && lines[lines.length - 1] !== "") {
  27. lines.push("");
  28. }
  29. lines.push(`${key}=${safeValue}`);
  30. }
  31. // 4. Write the updated content back to the file
  32. await Bun.write(`.env`, lines.join("\n"));
  33. // 5. Update the live process environment so your app can use it immediately
  34. process.env[key] = newValue;
  35. // console.log(`✅ Set ${key} to newly updated value in ${ENV_PATH}`);
  36. }