CodingNeed.

2 · Build one skill at a time · 18 MIN

Read and validate a JSON file

Reading bytes, parsing JSON and validating data are separate steps.

A file read returns text when you request UTF-8 decoding. JSON.parse converts correctly formatted text into JavaScript values but does not prove that the object has the fields your program expects. Check the shape after parsing. This example creates its own temporary directory, writes sample data, reads it back and removes the directory in finally. That cleanup also runs on failure. Do not point practice cleanup code at an unrelated directory or pass user-supplied paths into a server file read.

Identify the freshly created temporary directory. Separate readFile, JSON.parse and the shape check. Use Number.isInteger for the new field. Keep deletion restricted to the directory returned by mkdtemp.

Before you start

Install Node.js 22.12+ (or a supported newer LTS). Create a folder named codingneed-node. Open a terminal in that folder. Save ONE lesson example as lesson.mjs and run node lesson.mjs. No npm dependencies are required. HTTP lessons keep running until you press Ctrl+C; stop the previous server before starting another.

File for this example: lesson.mjs

New words, explained

encoding
The rule used to convert file bytes to text.
JSON
A text format for values, arrays and objects.
finally
A block executed when leaving try, including after errors.

Follow the example step by step

  1. Identify the freshly created temporary directory.
  2. Separate readFile, JSON.parse and the shape check.
  3. Use Number.isInteger for the new field.
  4. Keep deletion restricted to the directory returned by mkdtemp.

You are ready to move on when: A numeric positive minutes value is accepted. A numeric-looking string is rejected. Cleanup still runs after a validation failure.

Read the example

import {mkdtemp, writeFile, readFile, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
const folder = await mkdtemp(join(tmpdir(), 'codingneed-'));
try {
  const file = join(folder, 'topic.json');
  await writeFile(file, JSON.stringify({title:'Node.js'}), 'utf8');
  const data = JSON.parse(await readFile(file, 'utf8'));
  if (!data || typeof data.title !== 'string') throw new Error('title must be text');
  console.log(data.title);
} finally {
  await rm(folder, {recursive:true, force:true});
}
Check the expected output
Node.js is printed. The example’s own temporary folder is removed even if parsing or validation fails.

Your challenge

Add a minutes field and require it to be a positive integer. Test a valid value, a string and a negative number.

Solution cost: Discuss the operations in this small example; rendering and I/O costs depend on the host. time · Proportional to the example’s retained data. space

Common trap

Valid JSON can still contain the wrong application data.

Study the project implementation
import {mkdtemp, writeFile, readFile, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
const folder = await mkdtemp(join(tmpdir(), 'codingneed-'));
try {
  const file = join(folder, 'topic.json');
  await writeFile(file, JSON.stringify({title:'Node.js'}), 'utf8');
  const data = JSON.parse(await readFile(file, 'utf8'));
  if (!data || typeof data.title !== 'string') throw new Error('title must be text');
  console.log(data.title);
} finally {
  await rm(folder, {recursive:true, force:true});
}

Further reading: Official documentation

Next lesson: Receive an HTTP request and return JSON

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.