UNPKG

@adonisjs/env

Version:

Environment variable manager for Node.js

44 lines (43 loc) 1.4 kB
import { t as EnvLoader } from "../loader-KsjAiZ3e.js"; import { writeFile } from "node:fs/promises"; import splitLines from "split-lines"; import lodash from "@poppinss/utils/lodash"; var EnvEditor = class EnvEditor { #appRoot; #loader; #files = []; static async create(appRoot) { const editor = new EnvEditor(appRoot); await editor.load(); return editor; } constructor(appRoot) { this.#appRoot = appRoot; this.#loader = new EnvLoader(this.#appRoot, true); } async load() { this.#files = (await this.#loader.load()).filter((envFile) => envFile.fileExists && (envFile.path.endsWith(".env") || envFile.path.endsWith(".env.example"))).map((envFile) => { return { contents: splitLines(envFile.contents.trim()), path: envFile.path }; }); } add(key, value, withEmptyExampleValue = false) { this.#files.forEach((file) => { let entryIndex = file.contents.findIndex((line) => line.startsWith(`${key}=`)); entryIndex = entryIndex === -1 ? file.contents.length : entryIndex; if (withEmptyExampleValue && file.path.endsWith(".env.example")) lodash.set(file.contents, entryIndex, `${key}=`); else lodash.set(file.contents, entryIndex, `${key}=${value}`); }); } toJSON() { return this.#files; } async save() { await Promise.all(this.#files.map((file) => { return writeFile(file.path, file.contents.join("\n")); })); } }; export { EnvEditor };