Reading and validating a config file
A program that reads its settings from a file needs three steps: parse the file, fill in what the file left out, and refuse what the file got wrong. The format is JSON because it is text, it has no comments to argue about, and the language can parse it without a package. The third step is the one people skip, and it is the one that turns a mysterious failure at run time into a message at start-up.
The lesson reads a config from a temporary folder, merges it over a set of defaults, checks every value against a schema and reports the keys nobody knows. The programs print the problems they find and set an exit status, so the reader sees a small tool rather than a fragment.
Reading the JSON
The file is read with readFile and parsed with JSON.parse, and a broken file throws a SyntaxError that the program catches like any other error. The parsed value is a plain object, so a key that the file did not set answers undefined and not an exception.
The program writes a small config, reads it back, prints the sorted keys and a key that is missing, and then parses a string with a trailing comma to show the failure.
The file read.mjs:
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'config-'));
const file = join(dir, 'config.json');
await writeFile(file, JSON.stringify({ name: 'reports', port: 8080, debug: true }, null, 2) + '\n');
const config = JSON.parse(await readFile(file, 'utf8'));
console.log('the keys:', Object.keys(config).sort().join(', '));
console.log('the name:', config.name);
console.log('a key that is not there:', config.timeout);
console.log('it is an object:', typeof config === 'object');
try {
JSON.parse('{ "port": 8080, }');
} catch (error) {
console.log('a broken file gives:', error.name);
}
await rm(dir, { force: true, recursive: true });
node read.mjs
the keys: debug, name, port
the name: reports
a key that is not there: undefined
it is an object: true
a broken file gives: SyntaxError
The three keys came out sorted and the missing one came out as undefined, which is the value a defaults step has to notice. The trailing comma is the mistake JSON does not allow, and the name of the error is enough for a message: the position and the text are in the message of the error, which the exercises ask for.
Defaults and a merge
A set of defaults and a spread of the file gives the effective config in one line: every key of the file wins and every key it does not set keeps its default. The merge is shallow, so a nested object in the file replaces the whole nested object of the defaults and does not merge into it, which is the trap this section is about.
The program merges one flat config and one with a nested object, and prints both results as JSON.
The file defaults.mjs:
const defaults = { host: '127.0.0.1', port: 3000, retries: 3, debug: false };
const fromFile = { port: 8080, debug: true };
const config = { ...defaults, ...fromFile };
console.log('the merged config:', JSON.stringify(config));
console.log('the host came from the defaults:', config.host);
const nestedDefaults = { server: { host: '127.0.0.1', port: 3000 } };
const nestedFile = { server: { port: 8080 } };
console.log('a shallow merge loses the host:', JSON.stringify({ ...nestedDefaults, ...nestedFile }));
node defaults.mjs
the merged config: {"host":"127.0.0.1","port":8080,"retries":3,"debug":true}
the host came from the defaults: 127.0.0.1
a shallow merge loses the host: {"server":{"port":8080}}
The flat merge kept the host and took the port, and the nested merge lost the host entirely. The fix is a deep merge written by hand for the two levels a config usually has, or a schema in which a nested object is all or nothing, which is the easier rule to explain to whoever writes the file.
Validating the values
A schema here is an object that names a type per key, and the check is a loop over its entries. The check collects every problem instead of throwing on the first one, because a reader who has to fix a config wants the whole list. A wrong type is the most common mistake, and a number written as a string is the one that survives every other check.
The program checks a config with a port written as a string and a debug flag written as 'yes', prints the problems and leaves with a status of one.
The file validate.mjs:
const schema = { host: 'string', port: 'number', retries: 'number', debug: 'boolean' };
const config = { host: '127.0.0.1', port: '8080', retries: 3, debug: 'yes' };
const problems = [];
for (const [key, expected] of Object.entries(schema)) {
if (!(key in config)) {
problems.push(key + ': is missing');
} else if (typeof config[key] !== expected) {
problems.push(key + ': expected ' + expected + ', got ' + typeof config[key]);
}
}
console.log('the number of problems:', problems.length);
for (const problem of problems) {
console.log('problem:', problem);
}
if (problems.length > 0) {
process.exitCode = 1;
}
node validate.mjs
echo "exit code: $?"
the number of problems: 2
problem: port: expected number, got string
problem: debug: expected boolean, got string
exit code: 1
Two problems were reported in the order of the schema, and the status told the shell that the run failed. A value that is missing and a value of the wrong type are separate cases in the loop, and the first has a message of its own because the fix is different.
Unknown keys
A key the program does not know is usually a typo, and a typo in a config is silent: the default stays and the reader sees no effect. Reporting the unknown keys and naming the closest known one is the difference between a config that works and a config that is edited for an hour. The distance between two words is a small function, and two edits is a good threshold for a suggestion.
The program reports two unknown keys, suggests a correction for the one that is close to a real key, prints nothing for the one that is not, and sets the status to one.
The file unknown.mjs:
const known = ['debug', 'host', 'port', 'retries'];
const config = { host: '127.0.0.1', prot: 8080, debug: true, retries: 3, names: [] };
const distance = (left, right) => {
const row = [...Array(right.length + 1).keys()];
for (let i = 1; i <= left.length; i += 1) {
let previous = row[0];
row[0] = i;
for (let j = 1; j <= right.length; j += 1) {
const saved = row[j];
const change = previous + (left[i - 1] === right[j - 1] ? 0 : 1);
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, change);
previous = saved;
}
}
return row[right.length];
};
const closest = (word) =>
known.reduce((best, candidate) =>
distance(word, candidate) < distance(word, best) ? candidate : best,
);
const unknown = Object.keys(config).filter((key) => !known.includes(key)).sort();
console.log('the unknown keys:', unknown.join(', '));
for (const key of unknown) {
const suggestion = closest(key);
if (distance(key, suggestion) <= 2) {
console.log(key + ': did you mean ' + suggestion + '?');
} else {
console.log(key + ': is not a known key');
}
}
if (unknown.length > 0) {
process.exitCode = 1;
}
node unknown.mjs
echo "exit code: $?"
the unknown keys: names, prot
names: is not a known key
prot: did you mean port?
exit code: 1
prot is one letter from port and got a suggestion; names is nothing like a known key and got a plain report. A tool that does this at start-up has already paid for itself the first time someone writes a config by hand.
Exercises
- Add a required key to the schema and run the check on a config without it. Which message do you get?
- Make the merge deep for one nested object. How many lines does it take, and what happens to an array?
- Report the unknown keys sorted by name. Which call do you need?
- Parse a config with a trailing comma and print the message of the error. What does the position in the message tell you?
- Turn the validation into a function that returns the list of problems, and let the caller set the status. Which part of the program gets shorter?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does JSON.parse throw on a broken file?
Answer
A SyntaxError
The name of the error tells the caller that the text is not JSON.
-
What does a spread merge do with a nested object?
Answer
It replaces the whole nested object
The spread copies one level, so a nested default disappears when the file sets any nested key.
-
What does this program print?
const defaults = { port: 3000, debug: false }; const fromFile = { port: 8080 }; console.log(JSON.stringify({ ...defaults, ...fromFile }));Answer
{"port":8080,"debug":false}
The file wins where it has a key, and the default fills the key it leaves out.
-
Why validate a config at start-up?
Answer
The program fails with a clear message instead of later with a strange one
A wrong value found at start-up is a message; the same value found later is a bug report.
-
What does this program print?
const config = { port: "8080" }; console.log(typeof config.port === "number");Answer
false
A number in quotes is a string, and that is exactly the mistake the check catches.
-
What should a tool do with an unknown key?
Answer
Report it, suggest a known key and fail
A typo that nobody reports leaves the default in place and the reader puzzled.
-
What does this program print?
const known = ["host", "port"]; const config = { host: "x", prot: 1 }; console.log(Object.keys(config).filter((key) => !known.includes(key)).join(","));Answer
prot
The filter keeps the key that is not in the list of known keys.
-
What does JSON.parse give for a number in the file?
Answer
A JavaScript number
JSON has one number type, and the parser maps it to the number of the language.
-
Where does the lesson keep the config file?
Answer
In a temporary folder that the program removes
The program writes it, reads it and removes it, so a run leaves nothing behind.
-
Which check catches a port written as "8080"?
Answer
typeof value === "number"
The string is truthy and compares like a number, so only the type check notices it.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev