Dotenv File Parser
Parse .env files with comments, export prefixes, quoted values, escapes and multiline strings without mutating process.env.
Code
export function parseDotenv(input: string): Record<string, string> {
if (typeof input !== "string") throw new TypeError("input must be a string");
const escapes: Record<string, string> = { "\\": "\\", n: "\n", r: "\r", t: "\t", '"': '"' };
const result: Record<string, string> = {};
const lines = input.replace(/\r\n?/g, "\n").split("\n");
for (let index = 0; index < lines.length; index += 1) {
let line = lines[index]!.trim();
if (line === "" || line.startsWith("#")) continue;
if (line.startsWith("export ")) line = line.slice("export ".length).trim();
const match = /^([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(line);
if (!match) throw new SyntaxError("invalid dotenv line " + (index + 1));
const key = match[1]!;
let raw = match[2]!;
let value: string;
if (raw.startsWith('"')) {
while (!/(^|[^\\])"\s*(#.*)?$/.test(raw)) {
index += 1;
if (index >= lines.length) throw new SyntaxError("unterminated quoted value for " + key);
raw += "\n" + lines[index]!;
}
const end = raw.lastIndexOf('"');
value = raw.slice(1, end).replace(/\\([\\nrt"])/g, (_, character: string) => {
return escapes[character] ?? character;
});
} else if (raw.startsWith("'")) {
let end = 1;
while (end < raw.length) {
if (raw[end] === "'") {
if (raw[end + 1] === "'") {
end += 2;
continue;
}
break;
}
end += 1;
}
if (end >= raw.length) throw new SyntaxError("unterminated quoted value for " + key);
value = raw.slice(1, end).replace(/''/g, "'");
} else {
value = raw.replace(/\s+#.*$/, "").trim();
}
result[key] = value;
}
return result;
}How the snippet works
Count the function parseDotenv as the entire surface area of Dotenv File Parser.
Iteration is nested: for (let index = 0; index < lines.length; index += 1) frames the pass, while (!/(^|[^\\])"\s*(#.*)?$/.test(raw)) does the per-item step. The code refuses to proceed on bad state and throws TypeError and SyntaxError at its guard.
Watch out for
- The guard
typeof input !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The main signature reads export function parseDotenv(input: string)
The surface worth importing is parseDotenv; the helpers around it are private to the snippet.
Key statements
return escapes[character] ?? character;
if (index >= lines.length) throw new SyntaxError("unterminated quoted value for " + key);
if (end >= raw.length) throw new SyntaxError("unterminated quoted value for " + key);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- How are precondition violations signaled?
- The code refuses to continue: `TypeError` and `SyntaxError` is thrown while the state is still recoverable.
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `parseDotenv` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.