Reading a JSON file involves more than waiting for the disk. The file might be missing, its contents might not be valid JSON, or the parsed value might have the wrong fields. Async/await lets you write those steps in order while preserving the failures each step can produce.
In this example, a command reads one or more project reports. A valid file produces a short summary. A bad file produces an error, while other valid reports still appear.
Table of Contents
Prepare three small reports
Use Node.js 22 or later and create a folder named node-json-reports. There are no dependencies to install. Save the valid report below as site.json.
{"project":"CampCodes refresh","completed":3}
Save this deliberately incomplete document as invalid.json. It gives the parser a failure you can reproduce without depending on an unreliable network connection.
{"project":
Finally, save wrong-shape.json. It is valid JSON, but its completed count is a string rather than a number.
{"project":"CampCodes refresh","completed":"3"}
Read, parse, and validate
Save this program as report.mjs. The first function handles one file. The second starts the independent reads and collects every outcome. The final block turns those outcomes into command-line messages.
import { readFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
export async function readReport(path) {
let text;
try { text = await readFile(path, 'utf8'); }
catch (error) { throw new Error(`Cannot read file (${error.code ?? 'unknown error'}).`); }
let data;
try { data = JSON.parse(text); }
catch { throw new Error('Invalid JSON.'); }
if (!data || Array.isArray(data) || typeof data.project !== 'string'
|| !data.project.trim() || !Number.isSafeInteger(data.completed) || data.completed < 0) {
throw new Error('Expected a nonempty project name and a nonnegative integer completed count.');
}
return { project: data.project.trim(), completed: data.completed };
}
export async function summarize(paths) {
const results = await Promise.allSettled(paths.map(path => readReport(path)));
return results.map((result, index) => ({ path: paths[index], ...result }));
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const paths = process.argv.slice(2);
if (!paths.length) {
console.error('Usage: node report.mjs file.json [more.json ...]');
process.exitCode = 1;
} else {
for (const result of await summarize(paths)) {
if (result.status === 'fulfilled') {
console.log(`${result.path}: ${result.value.project} — ${result.value.completed} completed`);
} else {
console.error(`${result.path}: ${result.reason.message}`);
process.exitCode = 1;
}
}
}
}
Run a successful report
Open a terminal in the folder and run node report.mjs site.json. You should see:
site.json: CampCodes refresh — 3 completed
The await expression waits for the readFile promise to settle. Once it succeeds, the next line parses the returned text. JSON.parse is synchronous and can throw immediately. That is why reading and parsing have separate error messages.
The async function returns a promise even though its final return statement contains an ordinary object. A throw inside that function rejects its promise. The caller must await it or otherwise handle the rejection.
Keep useful results when one file fails
Run node report.mjs site.json invalid.json wrong-shape.json missing.json. Leave missing.json absent. The first report succeeds. The next three report invalid JSON, a schema mismatch, and ENOENT respectively.
The command sets a nonzero exit status when any file fails. On macOS and Linux you can inspect it with echo $? immediately afterward; in PowerShell use $LASTEXITCODE. The successful result remains available, but a calling script can still detect that the overall run needs attention.
Why use Promise.allSettled here?
The reports are independent, and this command is meant to display partial results. Promise.allSettled gives every input an outcome record. A fulfilled record contains value; a rejected record contains reason. Its result array follows input order, so the code can pair each result with its original path.
Promise.all is useful when the caller needs all operations to succeed before proceeding. Its rejection does not automatically cancel the other operations. Neither helper makes synchronous CPU-heavy work run in parallel; they coordinate promises.
Do not mistake valid JSON for valid data
A quoted count such as “3” is legal JSON. This program still rejects it because the report format requires a nonnegative safe integer. Empty project names, arrays, and null are rejected too. Decide whether a real application should convert inputs or reject them, then make that rule visible.
The read error includes the system error code but not a stack trace. A missing file is different from a malformed file. Replacing either with an empty successful object would hide the problem and make the output look more trustworthy than it is.
Where this version fits
Use it for a small set of local sample files. readFile loads each whole file into memory, and the map starts every requested read without a concurrency limit. A command accepting thousands of large files needs bounded concurrency, size rules, and possibly streaming.
Paths resolve from the terminal’s current directory. If the file is present but the command reports ENOENT, check where the terminal is running. You can also pass an explicit relative or absolute path. No file is modified by this program.
Download all the example files
The ZIP contains this original CampCodes example, a README, and an MIT license. No account, package installation, or paid service is needed.
References and verification
See Node.js readFile and MDN’s Promise.allSettled reference. This guide was rewritten with AI assistance on October 22, 2026. Automated checks on Node.js 24.9.0 covered a valid report, malformed JSON, invalid fields, a missing file, and mixed outcomes in input order. Command-line exit behavior was checked separately.
