Read and parse a JSON file with UTF-8 BOM stripping capabilities
npx @tessl/cli install tessl/npm-load-json-file@7.0.0A 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.
npm install load-json-fileimport { loadJsonFile, loadJsonFileSync } from "load-json-file";Note: This package is ES modules only and requires import statements. CommonJS require() is not supported.
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
});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>;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;/**
* 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[];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}`);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, '');
}
});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;
}
});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);
}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 stringloadJsonFile) and sync (loadJsonFileSync) versions availablebeforeParse to modify JSON string before parsing