← Runnable Projects

阅读中文版本

Dotenv File Loader

A Node module and CLI that reads a .env file, parses KEY=value lines with quoting and comments, and merges them into process.env without overwriting existing values.

beginnerjavascriptunverified

Project

node-env-loader

Entry point: env-loader.mjs

Install

node --version

Run

node env-loader.mjs .env

Test

node --test env-loader.test.mjs

Expected output

Prints the merged environment values and which keys were newly added versus already present.

Dependencies

  • node >=20

What it does

Loads a .env file into process.env with the conventions people expect: comments are ignored, quoted values keep their spaces, and real environment variables win over the file.

import { readFileSync } from 'node:fs';

export function parseEnv(text) {
  const out = {};
  for (const raw of text.split(/\r?\n/)) {
    const line = raw.trim();
    if (!line || line.startsWith('#')) continue;
    const eq = line.indexOf('=');
    if (eq < 0) continue;
    const key = line.slice(0, eq).trim();
    let value = line.slice(eq + 1).trim();
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
      value = value.slice(1, -1);
    }
    out[key] = value;
  }
  return out;
}

export function loadEnv(text, target = process.env) {
  const parsed = parseEnv(text);
  const added = [];
  for (const [key, value] of Object.entries(parsed)) {
    if (target[key] === undefined) { target[key] = value; added.push(key); }
  }
  return { added };
}

const file = process.argv[2] ?? '.env';
const { added } = loadEnv(readFileSync(file, 'utf8'));
console.log('loaded=' + added.join(','));

The CLI prints what it did so a misconfigured deployment is visible immediately rather than failing later with an undefined value.

Run and verify

printf 'APP_NAME="My App"\n# comment\nPORT=3000\n' > .env
node env-loader.mjs .env

Write a small .env with a commented line and a quoted value, then load it; existing process values are never overwritten.

Expected Output

With the sample file the program should add APP_NAME and PORT and skip the comment. The output is:

loaded=APP_NAME,PORT

The quoted value keeps its internal space, the comment line contributes nothing, and any key already present in the real environment is left untouched.

Limitations

It supports simple KEY=value lines and single or double quotes; multi-line values, variable expansion, and escaping are not implemented.