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
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
filePath | string | Path to the JSON (or JSONC) file to read. |
Returns
Section titled “Returns”T | null — The parsed value typed as T, or fallback on failure.
Examples
Section titled “Examples”Read and parse a JSON file
Section titled “Read and parse a JSON file”Returns the parsed value when the file exists and contains valid JSON.
Return null when the file is missing
Section titled “Return null when the file is missing”Returns null instead of throwing when the file does not exist.
Use a fallback value
Section titled “Use a fallback value”Returns the provided fallback when the file is missing or invalid.
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.
