CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-utility

A collection of useful TypeScript/JavaScript utilities for crypto, date, string, number, JSON operations and more.

Pending
Overview
Eval results
Files

json.mddocs/

JSON Operations

Safe JSON parsing and file I/O operations with proper error handling, directory creation, and configurable formatting options for robust data persistence and processing.

Capabilities

Strict JSON Parsing

Strict JSON parsing that ensures the result is an object type.

/**
 * Strict JSON parse that validates result is an object
 * @param content - JSON string to parse
 * @returns Parsed object (throws if not an object)
 */
function strictJSONParse<T extends object = object>(content: string): T;

Usage Examples:

import { strictJSONParse } from "utility";

// Valid object parsing
const user = strictJSONParse<{name: string, age: number}>('{"name": "Alice", "age": 30}');
// Result: { name: "Alice", age: 30 }

// Array parsing (throws error)
try {
  const invalid = strictJSONParse('[1, 2, 3]');
} catch (error) {
  // Error: JSON string is not object
}

// Primitive parsing (throws error)
try {
  const invalid = strictJSONParse('"string"');
} catch (error) {
  // Error: JSON string is not object
}

Synchronous JSON File Operations

Synchronous JSON file reading and writing with automatic directory creation.

/**
 * Read JSON file synchronously
 * @param filepath - Path to JSON file
 * @returns Parsed JSON content
 */
function readJSONSync<T = any>(filepath: string): T;

/**
 * Write JSON file synchronously with directory creation
 * @param filepath - Path to write JSON file
 * @param content - Content to write (string or object)
 * @param options - Formatting options
 */
function writeJSONSync(filepath: string, content: string | object, options?: JSONStringifyOptions): void;

interface JSONStringifyOptions {
  space?: number | string;
  replacer?: (this: any, key: string, value: any) => any;
}

Usage Examples:

import { readJSONSync, writeJSONSync } from "utility";

// Read JSON file
const config = readJSONSync<{port: number, host: string}>('./config.json');
// Result: parsed JSON object

// Write object to JSON file
writeJSONSync('./output.json', { 
  name: 'test', 
  value: 42,
  timestamp: new Date().toISOString()
});

// Write with custom formatting
writeJSONSync('./formatted.json', { data: 'value' }, { 
  space: 4,
  replacer: (key, value) => typeof value === 'string' ? value.toUpperCase() : value
});

// Write JSON string directly
writeJSONSync('./direct.json', '{"already": "json"}');

// Automatic directory creation
writeJSONSync('./nested/deep/path/file.json', { created: true });

Asynchronous JSON File Operations

Asynchronous JSON file reading and writing with promise-based API.

/**
 * Read JSON file asynchronously
 * @param filepath - Path to JSON file
 * @returns Promise resolving to parsed JSON content
 */
function readJSON<T = any>(filepath: string): Promise<T>;

/**
 * Write JSON file asynchronously with directory creation
 * @param filepath - Path to write JSON file
 * @param content - Content to write (string or object)
 * @param options - Formatting options
 * @returns Promise that resolves when write completes
 */
function writeJSON(filepath: string, content: string | object, options?: JSONStringifyOptions): Promise<void>;

Usage Examples:

import { readJSON, writeJSON } from "utility";

// Read JSON file asynchronously
const configData = await readJSON<{database: string}>('./config.json');
console.log(configData.database);

// Write JSON file asynchronously
await writeJSON('./async-output.json', {
  timestamp: Date.now(),
  data: [1, 2, 3, 4, 5]
});

// Batch operations
const promises = [
  writeJSON('./file1.json', { id: 1 }),
  writeJSON('./file2.json', { id: 2 }),
  writeJSON('./file3.json', { id: 3 })
];
await Promise.all(promises);

// With custom formatting
await writeJSON('./pretty.json', { 
  nested: { 
    data: 'value' 
  } 
}, { 
  space: 2 
});

// Error handling
try {
  const data = await readJSON('./nonexistent.json');
} catch (error) {
  console.error('File not found or invalid JSON');
}

JSON Formatting Options

Configuration options for JSON stringification with custom formatting and replacement.

interface JSONStringifyOptions {
  /**
   * A string or number for indentation (defaults to 2 spaces)
   */
  space?: number | string;
  
  /**
   * A function that transforms results or array of property names
   */
  replacer?: (this: any, key: string, value: any) => any;
}

Usage Examples:

import { writeJSONSync } from "utility";

// Tab indentation
writeJSONSync('./tabs.json', { data: 'value' }, { space: '\t' });

// No formatting (compact)
writeJSONSync('./compact.json', { data: 'value' }, { space: 0 });

// Custom replacer function
writeJSONSync('./filtered.json', { 
  public: 'visible',
  private: 'hidden',
  secret: 'confidential'
}, {
  space: 2,
  replacer: (key, value) => {
    if (key === 'secret') return undefined; // Remove secret fields
    return value;
  }
});

// Transform values
writeJSONSync('./transformed.json', { 
  date: new Date(),
  number: 42.123456
}, {
  space: 2,
  replacer: (key, value) => {
    if (value instanceof Date) return value.toISOString();
    if (typeof value === 'number') return Math.round(value * 100) / 100;
    return value;
  }
});

Install with Tessl CLI

npx tessl i tessl/npm-utility

docs

array.md

crypto.md

date.md

fs.md

function.md

index.md

json.md

number.md

object.md

optimize.md

string.md

timeout.md

web.md

tile.json