Deviopath › Node.js

Parse a .env File

Medium · Config

Packages like dotenv read a .env file into process.env. Write parseEnv(text) that returns an object of string values, using these rules (a simplified version of what dotenv does):

- Split into lines on \n (ignore a \r at the end of a line). Skip blank lines and lines whose first non-space character is #.

- An optional export prefix is ignored.

- Split at the FIRST =: the key is the trimmed text before it. Skip lines without = or with an empty key.

- Trim the value. If it starts with ' or " and the same quote appears again later, the value is the text between them, and anything after the closing quote is ignored. Inside single quotes the text is literal ('a\nb' stays a backslash and an n). Inside double quotes, \n turns into a real newline.

- Otherwise (unquoted), cut everything from the first # (space + #) and trim again. A # without a space before it is kept (http://x.com/#top).

- If a key appears twice, the later line wins.

Next: Split a Stream into Lines