Sequence NODE_240
Medium

Implement a Config Loader with Defaults

Node.js
Technical Specification

Create a config loader that merges default config, JSON file config, and environment variables (env has highest priority).

Input/Output Samples
Input:PORT default 3000, env PORT=5000
Output:Final port 5000
Optimal Logic Path
const fs = require("fs");

const defaults = {
  PORT: 3000,
  NODE_ENV: "development",
};

function loadConfig(path = "config.json") {
  let fileConfig = {};
  try {
    fileConfig = JSON.parse(fs.readFileSync(path, "utf8"));
  } catch {
    // ignore if file missing/invalid
  }
  const envConfig = {
    PORT: process.env.PORT,
    NODE_ENV: process.env.NODE_ENV,
  };
  return {
    ...defaults,
    ...fileConfig,
    ...Object.fromEntries(
      Object.entries(envConfig).filter(([, v]) => v !== undefined),
    ),
  };
}

module.exports = { loadConfig };
Architectural Deep-Dive
We merge default values with config file and then env, letting env override everything for deployment flexibility.