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

dumping.mddocs/

YAML Dumping

The dumping functionality in js-yaml provides comprehensive YAML serialization capabilities, converting JavaScript objects to YAML strings with extensive formatting and style control options.

Core Dumping Function

dump

Serializes a JavaScript object as a YAML document string.

function dump(input, options);

Parameters:

  • input (any): JavaScript value to serialize (object, array, string, number, boolean, null)
  • options (DumpOptions, optional): Serialization configuration options

Returns: YAML string representation of the input

Throws: YAMLException if input contains non-serializable values (unless skipInvalid: true)

Usage Examples:

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

// Basic serialization
const obj = {
  name: 'John Doe',
  age: 30,
  skills: ['JavaScript', 'YAML', 'Node.js'],
  active: true
};

const yamlString = yaml.dump(obj);
console.log(yamlString);

Dump Options

DumpOptions Interface

interface DumpOptions {
  indent?: number;
  noArrayIndent?: boolean;
  skipInvalid?: boolean;
  flowLevel?: number;
  styles?: object;
  schema?: Schema;
  sortKeys?: boolean | ((a: string, b: string) => number);
  lineWidth?: number;
  noRefs?: boolean;
  noCompatMode?: boolean;
  condenseFlow?: boolean;
  quotingType?: '"' | "'";
  forceQuotes?: boolean;
  replacer?: (key: string, value: any) => any;
}

Indentation Control

indent - Controls indentation width in spaces (default: 2):

yaml.dump(obj, { indent: 4 });
// Output with 4-space indentation

noArrayIndent - When true, doesn't add indentation level to array elements:

const data = { items: ['a', 'b', 'c'] };

// Default behavior
yaml.dump(data);
// items:
//   - a
//   - b

// With noArrayIndent: true
yaml.dump(data, { noArrayIndent: true });
// items:
// - a
// - b

Error Handling

skipInvalid - Skip invalid types instead of throwing errors:

const objWithFunction = {
  name: 'test',
  callback: function() { return 'hello'; },
  data: [1, 2, 3]
};

// Throws error by default
try {
  yaml.dump(objWithFunction);
} catch (e) {
  console.log('Cannot serialize function');
}

// Skip invalid types
const result = yaml.dump(objWithFunction, { skipInvalid: true });
// Only serializes 'name' and 'data', skips 'callback'

Flow vs Block Style

flowLevel - Controls when to switch from block to flow style (-1 = always block):

const nested = {
  level1: {
    level2: {
      level3: { key: 'value' }
    }
  }
};

// Always block style (default)
yaml.dump(nested, { flowLevel: -1 });

// Switch to flow at level 2
yaml.dump(nested, { flowLevel: 1 });
// level1:
//   level2: { level3: { key: value } }

Key Sorting

sortKeys - Sort object keys in output:

const unordered = { z: 1, a: 2, m: 3 };

// Sort alphabetically
yaml.dump(unordered, { sortKeys: true });
// a: 2
// m: 3  
// z: 1

// Custom sort function
yaml.dump(unordered, { 
  sortKeys: (a, b) => b.localeCompare(a) // Reverse alphabetical
});

Line Width Control

lineWidth - Maximum line width for text wrapping (default: 80, -1 = unlimited):

const longText = { description: 'A very long text that exceeds normal line width...' };

yaml.dump(longText, { lineWidth: 40 });
// description: >-
//   A very long text that exceeds normal
//   line width...

yaml.dump(longText, { lineWidth: -1 });
// No line wrapping

Reference Handling

noRefs - Disable object reference conversion for duplicate objects:

const shared = { shared: 'data' };
const obj = { ref1: shared, ref2: shared };

// Default: uses YAML references
yaml.dump(obj);
// ref1: &ref_0
//   shared: data
// ref2: *ref_0

// With noRefs: true
yaml.dump(obj, { noRefs: true });
// ref1:
//   shared: data
// ref2:
//   shared: data

String Quoting

quotingType - Preferred quote style for strings:

const strings = { single: "text with 'quotes'", double: 'text with "quotes"' };

yaml.dump(strings, { quotingType: '"' });
// Use double quotes when needed

yaml.dump(strings, { quotingType: "'" });
// Use single quotes when needed (default)

forceQuotes - Force quote all non-key strings:

const data = { key: 'simple text', number: '123' };

yaml.dump(data, { forceQuotes: true });
// key: 'simple text'
// number: '123'

Compatibility

noCompatMode - Disable YAML 1.1 compatibility features:

const booleans = { yes: true, no: false, on: true };

// Default: quotes ambiguous values for YAML 1.1 compatibility
yaml.dump(booleans);
// 'yes': true
// 'no': false

// With noCompatMode: true
yaml.dump(booleans, { noCompatMode: true });
// yes: true
// no: false

condenseFlow - Condense flow sequences and mappings:

const flow = { list: ['a', 'b', 'c'], map: { x: 1, y: 2 } };

yaml.dump(flow, { flowLevel: 0, condenseFlow: true });
// {list: [a,b,c], map: {x: 1,y: 2}}

Schema Control

schema - Specify schema for serialization:

yaml.dump(data, { schema: yaml.JSON_SCHEMA });
// Only uses JSON-compatible types

Value Transformation

replacer - Transform values during serialization:

const data = { 
  created: new Date('2023-01-01'),
  secret: 'password123',
  value: 42
};

yaml.dump(data, {
  replacer: (key, value) => {
    if (key === 'secret') return '[REDACTED]';
    if (value instanceof Date) return value.toISOString();
    return value;
  }
});

Type-Specific Styling

Control how specific YAML types are formatted using the styles option:

interface StylesMap {
  [tagName: string]: string;
}

Built-in Type Styles

!!null styles:

  • "canonical""~"
  • "lowercase""null" (default)
  • "uppercase""NULL"
  • "camelcase""Null"

!!int styles:

  • "binary""0b1101"
  • "octal""0o15"
  • "decimal""13" (default)
  • "hexadecimal""0xD"

!!bool styles:

  • "lowercase""true", "false" (default)
  • "uppercase""TRUE", "FALSE"
  • "camelcase""True", "False"

!!float styles:

  • "lowercase"".nan", ".inf" (default)
  • "uppercase"".NAN", ".INF"
  • "camelcase"".NaN", ".Inf"

Style Usage Example

const data = {
  active: null,
  count: 42,
  flag: true,
  ratio: Number.POSITIVE_INFINITY
};

yaml.dump(data, {
  styles: {
    '!!null': 'canonical',     // Use ~ for null
    '!!int': 'hexadecimal',    // Use hex for integers
    '!!bool': 'uppercase',     // Use TRUE/FALSE
    '!!float': 'uppercase'     // Use .INF/.NAN
  }
});

// Output:
// active: ~
// count: 0x2A
// flag: TRUE
// ratio: .INF

Common Patterns

Configuration File Generation

function generateConfig(config) {
  return yaml.dump(config, {
    indent: 2,
    lineWidth: 120,
    sortKeys: true,
    noCompatMode: true,
    styles: {
      '!!null': 'lowercase',
      '!!bool': 'lowercase'
    }
  });
}

Data Export with Formatting

function exportData(data, format = 'readable') {
  const options = {
    readable: {
      indent: 2,
      lineWidth: 80,
      flowLevel: -1
    },
    compact: {
      indent: 0,
      lineWidth: -1,
      flowLevel: 0,
      condenseFlow: true
    },
    safe: {
      skipInvalid: true,
      noRefs: true,
      schema: yaml.CORE_SCHEMA
    }
  };
  
  return yaml.dump(data, options[format] || options.readable);
}

docs

dumping.md

errors.md

index.md

loading.md

schemas.md

tile.json