CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-js-yaml

YAML 1.2 parser and serializer for JavaScript environments with complete specification support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

loading.mddocs/

YAML Loading

The loading functionality in js-yaml provides comprehensive YAML parsing capabilities, supporting both single and multi-document YAML sources with extensive configuration options.

Core Loading Functions

load

Parses a single YAML document from a string.

function load(input, options);

Parameters:

  • input (string): YAML string to parse
  • options (LoadOptions, optional): Parsing configuration options

Returns: The parsed JavaScript value (object, array, string, number, boolean, null, or undefined)

Throws: YAMLException on parsing errors

Usage Examples:

const yaml = require('js-yaml');

// Basic parsing
const simple = yaml.load('hello: world');
// Result: { hello: 'world' }

// Parse different data types
const data = yaml.load(`
name: John Doe
age: 30
active: true
skills:
  - JavaScript
  - YAML
  - Node.js
`);

// With options
const doc = yaml.load(yamlString, {
  filename: 'config.yml',
  schema: yaml.JSON_SCHEMA,
  onWarning: (warning) => console.warn(warning.toString())
});

loadAll

Parses multiple YAML documents from a single string, separated by --- document separators.

function loadAll(input, iterator, options);
function loadAll(input, options);

Parameters:

  • input (string): YAML string containing multiple documents
  • iterator (function, optional): Function called for each parsed document
  • options (LoadOptions, optional): Parsing configuration options

Returns: Array of parsed documents (if no iterator provided)

Usage Examples:

const yaml = require('js-yaml');

const multiDoc = `
---
name: Document 1
type: config
---
name: Document 2  
type: data
---
items: [1, 2, 3]
`;

// Using iterator
yaml.loadAll(multiDoc, (doc) => {
  console.log('Parsed document:', doc);
});

// Getting array of documents
const docs = yaml.loadAll(multiDoc);
console.log(`Found ${docs.length} documents`);

Loading Options

LoadOptions Interface

interface LoadOptions {
  filename?: string;
  onWarning?: (warning: YAMLException) => void;
  schema?: Schema;
  json?: boolean;
}

filename

Specifies a filename to be used in error and warning messages for better debugging.

const doc = yaml.load(yamlContent, {
  filename: 'config.yaml'
});

onWarning

Callback function to handle parsing warnings without stopping the parsing process.

const doc = yaml.load(yamlContent, {
  onWarning: (warning) => {
    console.warn(`YAML Warning: ${warning.message}`);
    console.warn(`Location: line ${warning.mark.line + 1}, column ${warning.mark.column + 1}`);
  }
});

schema

Specifies which YAML schema to use for parsing. Controls which types are recognized.

// Use JSON schema (no custom types)
const doc = yaml.load(yamlContent, {
  schema: yaml.JSON_SCHEMA
});

// Use default schema (all supported types)
const doc = yaml.load(yamlContent, {
  schema: yaml.DEFAULT_SCHEMA
});

Available schemas:

  • yaml.FAILSAFE_SCHEMA - Only strings, sequences, and mappings
  • yaml.JSON_SCHEMA - JSON-compatible types (null, boolean, integer, float)
  • yaml.CORE_SCHEMA - Same as JSON_SCHEMA
  • yaml.DEFAULT_SCHEMA - All supported types including timestamps, binary, etc.

json

When true, enables JSON compatibility mode where duplicate keys in mappings will override previous values instead of throwing an error.

const yamlWithDuplicates = `
key: first value
key: second value
`;

// Normally throws error
try {
  yaml.load(yamlWithDuplicates);
} catch (e) {
  console.log('Error: duplicate key');
}

// With json: true, uses last value
const doc = yaml.load(yamlWithDuplicates, { json: true });
console.log(doc.key); // "second value"

Error Handling

Loading functions throw YAMLException for parsing errors:

try {
  const doc = yaml.load('invalid: yaml: syntax');
} catch (e) {
  if (e instanceof yaml.YAMLException) {
    console.log('YAML Error:', e.reason);
    console.log('Position:', e.mark);
    console.log('Snippet:', e.mark.snippet);
  }
}

Common Patterns

Safe File Loading

const fs = require('fs');
const yaml = require('js-yaml');

function loadYamlFile(filepath) {
  try {
    const content = fs.readFileSync(filepath, 'utf8');
    return yaml.load(content, { filename: filepath });
  } catch (e) {
    if (e instanceof yaml.YAMLException) {
      console.error(`YAML parsing error in ${filepath}:`, e.message);
    } else {
      console.error(`File read error:`, e.message);
    }
    throw e;
  }
}

Configuration Loading with Validation

function loadConfig(yamlString) {
  const config = yaml.load(yamlString, {
    schema: yaml.CORE_SCHEMA, // Restrict to basic types
    onWarning: (warning) => console.warn(`Config warning: ${warning.message}`)
  });
  
  // Validate required fields
  if (!config.database || !config.server) {
    throw new Error('Missing required configuration sections');
  }
  
  return config;
}

docs

dumping.md

errors.md

index.md

loading.md

schemas.md

tile.json