env/update_env_variable.ts

Write updates to .env files while preserving formatting.

update_env_content is the one env-file writer: a pure line rebuild that update_env_variable (read, update, write) and dev/setup.ts's setup_env_file both build on, so every value lands quoted and escaped the same way and round-trips through parse_dotenv.

view source

Declarations
#

2 declarations

update_env_content
#

env/update_env_variable.ts view source

(content: string, key: string, value: string): string import {update_env_content} from '@fuzdev/fuz_app/env/update_env_variable.js';

Set key to value in dotenv content, returning the new content. Preserves existing formatting, comments, and other variables.

Behavior:

  • Duplicate keys: updates the LAST occurrence (matches dotenv behavior)
  • Inline comments: preserved after the value (e.g., KEY=value # comment)
  • Quote style: a quoted value stays quoted; an unquoted one stays bare unless the new value would not read back bare (surrounding whitespace, a # comment marker, a leading quote, a line break), which is quoted
  • export prefix: preserved when updating an export KEY=… line
  • Absent key: appended as a quoted assignment

The line is rebuilt from its parts, so no character of value ($&, `` $ `, $', \) is interpreted.

content

dotenv file content ('' for a new file)

type string

key

the environment variable name

type string

value

the new value

type string

returns

string

the updated content

update_env_variable
#

env/update_env_variable.ts view source

(deps: FsReadDeps & FsWriteDeps & Partial<FsRemoveDeps>, env_path: string, key: string, value: string): Promise<void> import {update_env_variable} from '@fuzdev/fuz_app/env/update_env_variable.js';

Updates or adds an environment variable in an env file — read, update_env_content, then an atomic replace at mode 0o600 (an env file holds secrets, so the fresh owner-only inode also tightens a permissive hand-made one). A missing file is created.

A read-modify-write: a concurrent writer's update can be lost (the last replace wins), though the file is never left half-written.

deps

file read and write capabilities; pass remove too for best-effort temp cleanup on a failed write

env_path

path to the env file

type string

key

the environment variable name (e.g., 'SOME_CONFIGURATION_KEY')

type string

value

the new value for the environment variable

type string

returns

Promise<void>

throws

  • Error - if the read or the write fails

mutates

  • filesystem — atomically replaces `env_path` at mode `0o600`

Depends on
#

Imported by
#