Skip to content

safeReadJsonFile

Reads a file and parses its contents as JSON, returning null (or a fallback) on any failure — a missing/unreadable file and invalid content are both treated the same way.

Also tolerates JSONC (line/block comments and trailing commas — the dialect used by tsconfig.json, VS Code’s settings.json, etc.): strict JSON.parse is tried first, and only on failure is the content re-parsed with comments/trailing commas stripped, so plain JSON pays no extra cost.

Unlike readFileSync + JSON.parse, this never throws.

Available since v3.0.6

import { safeReadJsonFile } from '@helpers4/node';
// or, from the all-in-one package (same code, one install):
import { safeReadJsonFile } from 'helpers4/node';
safeReadJsonFile<T>(filePath: string): T | null
ParameterTypeDescription
filePathstringPath to the JSON (or JSONC) file to read.

T | null — The parsed value typed as T, or fallback on failure.

Returns the parsed value when the file exists and contains valid JSON.

safeReadJsonFile<{ name: string }>('./package.json')
// => { name: 'my-package', ... }

Returns null instead of throwing when the file does not exist.

safeReadJsonFile('./does-not-exist.json')
// => null

Returns the provided fallback when the file is missing or invalid.

safeReadJsonFile('./does-not-exist.json', {})
// => {}

Also reads JSONC (comments + trailing commas)

Section titled “Also reads JSONC (comments + trailing commas)”

tsconfig.json/settings.json-style content — line/block comments and a trailing comma — parses too.

safeReadJsonFile('./tsconfig.json')
// {
//   // enable strict type-checking
//   "compilerOptions": { "strict": true },
// }
// => { compilerOptions: { strict: true } }

View source on GitHub