Use the dotenv edit utilities when you need to update a .env* file in place without destroying comments, spacing, ordering, unknown lines, or line endings.
import { editDotenvText } from '@karmaniverous/get-dotenv';
const next = editDotenvText('A=1\n# keep\nB=2\n', {
A: 'updated',
UNUSED: null,
});
import { editDotenvFile } from '@karmaniverous/get-dotenv';
await editDotenvFile(
{ API_URL: 'https://example.com', UNUSED: null },
{
paths: ['./'],
scope: 'env',
privacy: 'private',
env: 'dev',
dotenvToken: '.env',
privateToken: 'local',
},
);
paths only (directories).
searchOrder: 'reverse' (default): last path wins.searchOrder: 'forward': first path wins.<target>.<templateExtension> (default template), copied to the target beside it first; else (env scope) the shared env template.scope: 'env' only): if neither the target nor its env-specific template exists, a shared template is tried next. It's named the same way as the env target, but with a fixed token (sharedEnvTemplateToken, default 'env') in place of the env name — e.g. .env.env.local.template for .env.<env>.local, or .env.env.template for .env.<env>. An env-specific template in any path beats a shared template in any path. Global scope never uses this fallback.{ path, createdFromTemplate, changed }.scope: 'global', privacy: 'public' → <dotenvToken>scope: 'env', privacy: 'public' → <dotenvToken>.<env>scope: 'global', privacy: 'private' → <dotenvToken>.<privateToken>scope: 'env', privacy: 'private' → <dotenvToken>.<env>.<privateToken>If scope: 'env' and neither env nor defaultEnv can be resolved, editDotenvFile throws.
null deletes key assignment lines (default).undefined skips (default).mode: 'merge' (default) updates and appends; mode: 'sync' upserts: the file ends up with exactly the given keys (updated in place, missing ones appended, others deleted; comments kept).-o): bare when safe, else the line's quote style, double, single or backtick quotes; a value no form can hold throws, naming the key.For advanced use:
parseDotenvDocument(text) → DotenvDocumentapplyDotenvEdits(doc, updates, opts?) → DotenvDocumentrenderDotenvDocument(doc, eolMode?) → stringbuildDotenvTargetFilename(opts) → target filenameresolveDotenvTarget(opts) → { targetPath, templatePath?, filename }