CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-yaml

JavaScript parser and stringifier for YAML documents with complete YAML 1.1 and 1.2 support

Overview
Eval results
Files

parse-stringify.mddocs/

Parse & Stringify

Simple parsing and stringifying functions for converting between YAML strings and JavaScript values. This is the most commonly used API layer, perfect for configuration files, data serialization, and straightforward YAML processing.

Capabilities

Parse Function

Parses a YAML string into JavaScript values. Supports single document parsing with comprehensive error handling and reviver function support similar to JSON.parse.

/**
 * Parse YAML string into JavaScript values
 * @param src - YAML string to parse
 * @param reviver - Optional reviver function for transforming values
 * @param options - Parsing and schema options
 * @returns Parsed JavaScript value
 */
function parse(src: string, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions): any;
function parse(src: string, reviver: Reviver, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions): any;

type Reviver = (key: unknown, value: unknown) => unknown;

Usage Examples:

import { parse } from "yaml";

// Basic usage
const config = parse(`
database:
  host: localhost
  port: 5432
  credentials:
    username: admin
    password: secret
`);
// Result: { database: { host: 'localhost', port: 5432, credentials: { username: 'admin', password: 'secret' } } }

// With reviver function
const data = parse('count: "42"', (key, value) => {
  if (key === 'count') return parseInt(value as string);
  return value;
});
// Result: { count: 42 }

// With options
const strictData = parse(`
name: John
age: 30
`, {
  strict: true,
  prettyErrors: true
});

Stringify Function

Converts JavaScript values to YAML strings. Supports replacer functions, custom formatting options, and complete control over output style.

/**
 * Convert JavaScript values to YAML string
 * @param value - Value to convert to YAML
 * @param replacer - Optional replacer function or array for filtering
 * @param options - Formatting and schema options
 * @returns YAML string representation
 */
function stringify(
  value: any,
  options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions
): string;

function stringify(
  value: any,
  replacer?: Replacer | null,
  options?: string | number | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions)
): string;

type Replacer = (key: string, value: any) => any | Array<string | number>;

Usage Examples:

import { stringify } from "yaml";

// Basic usage
const yamlString = stringify({
  name: "Alice",
  hobbies: ["reading", "coding", "music"],
  address: {
    city: "New York",
    zipcode: 10001
  }
});
// Result:
// name: Alice
// hobbies:
//   - reading
//   - coding
//   - music
// address:
//   city: New York
//   zipcode: 10001

// With replacer function
const filtered = stringify({
  username: "john",
  password: "secret",
  email: "john@example.com"
}, (key, value) => {
  if (key === 'password') return '***';
  return value;
});

// With formatting options
const formatted = stringify(data, {
  indent: 4,
  blockQuote: 'literal',
  lineWidth: 120
});

// Shorthand indent specification
const indented = stringify(data, null, 2); // 2-space indent

Error Handling

Both functions handle errors gracefully and provide detailed error information for debugging.

// Parse errors are thrown as YAMLParseError
try {
  const data = parse('invalid: yaml: content:');
} catch (error) {
  if (error instanceof YAMLParseError) {
    console.log(error.message); // Detailed error message
    console.log(error.pos);     // [start, end] position in source
    console.log(error.linePos); // { line: number, col: number }
  }
}

// Stringify typically doesn't throw but may warn
const result = stringify(undefined, { keepUndefined: false });
// Returns undefined instead of throwing

Option Interfaces

ParseOptions

interface ParseOptions {
  /** Keep CST nodes in parsed output */
  keepCstNodes?: boolean;
  /** Keep node type information */
  keepNodeTypes?: boolean;
  /** Keep Uint8Array instances as-is in JSON output */
  keepBlobsInJSON?: boolean;
  /** Maximum number of alias nodes to resolve */
  maxAliasCount?: number;
  /** Add line/column position info to errors */
  prettyErrors?: boolean;
  /** Callback for each new line during parsing */
  lineCounter?: LineCounter | boolean;
  /** Log level for warnings and errors */
  logLevel?: 'silent' | 'error' | 'warn' | 'debug';
  /** Enable strict parsing mode */
  strict?: boolean;
}

ToStringOptions

interface ToStringOptions {
  /** Use block quote style for multiline strings */
  blockQuote?: boolean | 'folded' | 'literal';
  /** Default type for object keys */
  defaultKeyType?: Scalar.Type | null;
  /** Default type for string values */
  defaultStringType?: Scalar.Type;
  /** Include document directives */
  directives?: boolean | null;
  /** Number of spaces for indentation */
  indent?: number;
  /** Use block style for sequences */
  indentSeq?: boolean | null;
  /** Maximum line width before folding */
  lineWidth?: number;
  /** Minimum width for single-line collections */
  minContentWidth?: number;
  /** Use null instead of empty for null values */
  nullStr?: string;
  /** Use single quotes by default */
  singleQuote?: boolean | null;
}

DocumentOptions

interface DocumentOptions {
  /** Document schema version */
  version?: '1.1' | '1.2' | 'next';
  /** Custom tags to include */
  customTags?: (TagId | Tag)[];
  /** Log level for this document */
  logLevel?: 'silent' | 'error' | 'warn' | 'debug';
  /** Schema to use for parsing */
  schema?: 'core' | 'failsafe' | 'json' | 'yaml-1.1';
  /** Sort object keys */
  sortMapEntries?: boolean | ((a: Pair, b: Pair) => number);
  /** Anchor prefix for generated anchors */
  anchorPrefix?: string;
  /** Keep undefined values */
  keepUndefined?: boolean;
}

Install with Tessl CLI

npx tessl i tessl/npm-yaml

docs

ast-nodes.md

document-processing.md

error-handling.md

index.md

parse-stringify.md

parser-infrastructure.md

schema-configuration.md

tree-traversal.md

type-guards.md

utilities.md

tile.json