or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-load-json-file

Read and parse a JSON file with UTF-8 BOM stripping capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/load-json-file@7.0.x

To install, run

npx @tessl/cli install tessl/npm-load-json-file@7.0.0

index.mddocs/

load-json-file

A simple and reliable utility for reading and parsing JSON files in Node.js applications. It offers both asynchronous and synchronous APIs with built-in UTF-8 BOM stripping capabilities, ensuring proper handling of JSON files regardless of their encoding. This package is ES modules only and requires Node.js with ES module support.

Package Information

  • Package Name: load-json-file
  • Package Type: npm
  • Language: JavaScript (ES modules only) with TypeScript definitions
  • Node.js Requirements: ^12.20.0 || ^14.13.1 || >=16.0.0
  • Installation: npm install load-json-file

Core Imports

import { loadJsonFile, loadJsonFileSync } from "load-json-file";

Note: This package is ES modules only and requires import statements. CommonJS require() is not supported.

Basic Usage

import { loadJsonFile, loadJsonFileSync } from "load-json-file";

// Async usage
const config = await loadJsonFile('config.json');
console.log(config);

// Sync usage  
const packageInfo = loadJsonFileSync('package.json');
console.log(packageInfo.name);

// With options
const data = await loadJsonFile('data.json', {
  beforeParse: jsonString => jsonString.replace(/\\/g, '/'), // Transform before parsing
  reviver: (key, value) => key === 'date' ? new Date(value) : value // Transform values
});

Capabilities

Asynchronous JSON File Loading

Reads and parses a JSON file asynchronously with UTF-8 BOM stripping.

/**
 * Read and parse a JSON file asynchronously
 * @param filePath - Path to the JSON file to read
 * @param options - Optional parsing configuration
 * @returns Promise that resolves to the parsed JSON data
 */
function loadJsonFile<ReturnValueType = JsonValue>(
  filePath: string, 
  options?: Options
): Promise<ReturnValueType>;

Synchronous JSON File Loading

Reads and parses a JSON file synchronously with UTF-8 BOM stripping.

/**
 * Read and parse a JSON file synchronously
 * @param filePath - Path to the JSON file to read
 * @param options - Optional parsing configuration
 * @returns The parsed JSON data
 */
function loadJsonFileSync<ReturnValueType = JsonValue>(
  filePath: string, 
  options?: Options
): ReturnValueType;

Types

/**
 * Configuration options for JSON parsing
 */
interface Options {
  /**
   * Function to transform the JSON string before parsing
   * Useful for preprocessing the raw JSON content
   */
  readonly beforeParse?: BeforeParse;
  
  /**
   * Function to transform parsed values during JSON.parse
   * See JSON.parse reviver parameter documentation
   */
  readonly reviver?: Reviver;
}

/**
 * Function type for transforming JSON string before parsing
 */
type BeforeParse = (data: string) => string;

/**
 * Function type for JSON.parse reviver parameter
 */
type Reviver = (this: unknown, key: string, value: unknown) => unknown;

/**
 * Represents any valid JSON value type (from type-fest)
 */
type JsonValue = string | number | boolean | null | {[Key in string]?: JsonValue} | JsonValue[];

Usage Examples

Basic File Loading

import { loadJsonFile } from "load-json-file";

// Load configuration
const config = await loadJsonFile('./config.json');

// Load package.json
const packageInfo = await loadJsonFile('./package.json');
console.log(`Loading ${packageInfo.name} v${packageInfo.version}`);

Using beforeParse Option

import { loadJsonFile } from "load-json-file";

// Remove comments from JSON before parsing
const data = await loadJsonFile('./config-with-comments.json', {
  beforeParse: (jsonString) => {
    // Remove single-line comments (simplified example)
    return jsonString.replace(/\/\/.*$/gm, '');
  }
});

Using reviver Option

import { loadJsonFile } from "load-json-file";

// Transform date strings to Date objects
const userData = await loadJsonFile('./user-data.json', {
  reviver: (key, value) => {
    if (key.endsWith('Date') && typeof value === 'string') {
      return new Date(value);
    }
    return value;
  }
});

Synchronous Usage

import { loadJsonFileSync } from "load-json-file";

try {
  const config = loadJsonFileSync('./config.json');
  console.log('Config loaded:', config);
} catch (error) {
  console.error('Failed to load config:', error.message);
}

Type-Safe Usage with TypeScript

import { loadJsonFile } from "load-json-file";

interface Config {
  apiUrl: string;
  timeout: number;
  features: string[];
}

// Type-safe loading
const config = await loadJsonFile<Config>('./config.json');
console.log(config.apiUrl); // TypeScript knows this is a string

Key Features

  • UTF-8 BOM Stripping: Automatically removes UTF-8 BOM using TextDecoder for consistent parsing
  • Dual API: Both async (loadJsonFile) and sync (loadJsonFileSync) versions available
  • Custom Transformations: Support for beforeParse to modify JSON string before parsing
  • Reviver Support: Full JSON.parse reviver functionality for value transformations
  • TypeScript Support: Complete type definitions with generic return types
  • Zero Dependencies: No external dependencies, uses only Node.js built-in modules
  • ES Module Only: Pure ES module format, requires Node.js with ES module support