Skip to content
jshacks.dev
Node.js

Load config from a JSON or env file

Load app config from either a config.json or a .env file in Node.js 24, picking JSON.parse or util.parseEnv by extension, with no packages.

2 min read
Summarize in AI

Some teams ship config.json, others a .env file, and a tool that supports both should not care which. Pick the parser by extension and return the same plain object either way.

config.mjsJavaScript
import { readFile, writeFile } from 'node:fs/promises';
import { extname, basename } from 'node:path';
import { parseEnv } from 'node:util';

async function loadConfig(path) {
  const text = await readFile(path, 'utf8');
  if (extname(path) === '.json') return JSON.parse(text);
  if (basename(path).startsWith('.env')) return parseEnv(text);
  throw new Error(`unsupported config file: ${path}`);
}

await writeFile('config.json', '{ "port": 8080, "debug": true }');
await writeFile('.env.local', 'PORT=8080\nDEBUG=true\n# comment\nNAME="my app"\n');

console.log(await loadConfig('config.json'));
console.log(await loadConfig('.env.local'));
Text
{ port: 8080, debug: true }
{ PORT: '8080', DEBUG: 'true', NAME: 'my app' }

util.parseEnv, added in Node.js 21.7.0 and 20.12.0, parses .env text into an object without touching process.env, so loading a config file has no side effects. It drops comments and strips the quotes. extname is no help for .env.local, whose extension it reports as .local, which is why the code checks the base name instead. See util.parseEnv.

The two formats do not give the same types: JSON keeps 8080 a number and true a boolean, while every .env value is a string, and the key names follow each format's own casing. Normalise before use, as in merge environment config with defaults. JSON.parse throws on a trailing comma, so report the file name with the error.

Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.