Skip to content

Latest commit

 

History

History
63 lines (50 loc) · 2.1 KB

File metadata and controls

63 lines (50 loc) · 2.1 KB
name json-file-tool
description Reads and writes JSON files on the local filesystem, with optional schema validation.
context node

JsonFileTool

Reads and writes JSON files on the local filesystem. Optionally validates the parsed value through a schema (any object with a .parse(unknown): T method — compatible with Zod, Valibot, and similar). readJson returns null when the file is missing; writeJson returns a Result so the caller can handle failures. OrThrow variants throw.

Interface

interface IJsonFileTool {
  /** Parses and returns the JSON file contents. Returns null if missing or unparseable. */
  readJson<T>(path: string, params?: ReadJsonParams<T>): T | null;
  /** Parses and returns the JSON file contents. Throws if missing, unparseable, or schema validation fails. */
  readJsonOrThrow<T>(path: string, params?: ReadJsonParams<T>): T;
  /** Serialises data to JSON and writes it. Creates parent directories as needed. */
  writeJson(path: string, data: unknown): Result<void, FileWriteError>;
  /** Serialises data to JSON and writes it. Creates parent directories as needed. Throws on failure. */
  writeJsonOrThrow(path: string, data: unknown): void;
}

interface ReadJsonParams<T> {
  /** Optional schema to validate the parsed value. Must have a `.parse(unknown): T` method. */
  schema?: JsonSchema<T>;
}

Usage

With DI

import { Container } from "@webiny/di";
import {
  JsonFileTool,
  JsonFileToolFeature,
  FileToolFeature,
  DirectoryToolFeature,
  PinoLoggerFeature
} from "@webiny/stdlib/node";

const container = new Container();
PinoLoggerFeature.register(container);
DirectoryToolFeature.register(container);
FileToolFeature.register(container);
JsonFileToolFeature.register(container);

const json = container.resolve(JsonFileTool);
json.writeJsonOrThrow("/tmp/config.json", { version: 1 });
const config = json.readJsonOrThrow<{ version: number }>("/tmp/config.json");

Without DI

import { createJsonFileTool } from "@webiny/stdlib/node";

const json = createJsonFileTool();
const data = json.readJson("/tmp/config.json"); // unknown | null