Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท util, assert and the Test Runner

Node.js util.parseEnv() function

Reference for util.parseEnv() in Node.js: turn the text of a .env file into an object, with the rules for quotes, comments, export and multi-line values.

util.parseEnv(content) takes the text of a .env file and returns a plain object of key-value pairs. It only parses: it does not read files and it does not touch process.env.

That makes it the pure counterpart of process.loadEnvFile(), which reads a file and copies the values into the environment. Use parseEnv() when you want the values as data, for example to merge several files or to test configuration code.

NODE
import { parseEnv } from "node:util";

const env = parseEnv("PORT=3000\nNAME=demo");
// { PORT: '3000', NAME: 'demo' }

Try it

Node.js Parsing a small .env text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Escapes, spaces and merging with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
util.parseEnv(content: string): object
Name Description
content The text of a .env file.

Returns: an object mapping each name to its string value. All values are strings.

Errors: a non-string argument throws ERR_INVALID_ARG_TYPE. Lines that are not valid assignments are skipped rather than reported.

Usage notes

  • Every value is a string. Convert yourself with Number(env.PORT) or env.DEBUG === "true".
  • Lines starting with # are comments, and an unquoted value stops at #. Inside quotes a # is kept.
  • Double, single and backtick quotes are supported. Double-quoted values turn \n into a real newline; single-quoted values stay literal.
  • A leading export is accepted, so files written for a shell often work unchanged.
  • Whitespace around the name and around an unquoted value is trimmed.
  • There is no variable expansion: B=${A} stays the literal text ${A}.
  • Quoted values may span several lines, which is handy for keys and certificates.