js-yaml vs yaml vs yamljs
YAML Parsing and Stringifying
js-yamlyamlyamljsSimilar Packages:

YAML Parsing and Stringifying

YAML (YAML Ain't Markup Language) is a human-readable data serialization format often used for configuration files, data exchange, and more. In JavaScript, libraries like js-yaml, yaml, and yamljs provide tools for parsing YAML files into JavaScript objects and stringifying objects back into YAML format. These libraries are essential for applications that need to read from or write to YAML files, offering features like support for complex data types, custom serialization, and more. js-yaml is a widely-used library known for its simplicity and performance, while yaml offers a modern API with advanced features like streaming and custom tags. yamljs, on the other hand, focuses on ease of use and provides a straightforward interface for working with YAML in JavaScript.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
js-yaml06,5921.44 MB717 hours agoMIT
yaml01,674686 kB392 months agoISC
yamljs0886-539 years agoMIT

Feature Comparison: js-yaml vs yaml vs yamljs

Parsing and Stringifying

  • js-yaml:

    js-yaml provides efficient parsing and stringifying of YAML, supporting complex data structures, custom tags, and error handling. It is known for its reliability and performance, making it suitable for a wide range of applications.

  • yaml:

    yaml offers advanced parsing and stringifying capabilities with support for streaming, custom tags, and more. It is designed for performance and flexibility, allowing for better handling of large YAML files and complex data types.

  • yamljs:

    yamljs offers basic parsing and stringifying of YAML with a focus on simplicity. It supports standard YAML features but lacks some of the advanced capabilities found in js-yaml and yaml, making it more suitable for straightforward use cases.

Streaming Support

  • js-yaml:

    js-yaml does not natively support streaming for parsing or stringifying YAML. It processes the entire input at once, which can be a limitation for very large YAML files.

  • yaml:

    yaml provides built-in streaming support for both parsing and stringifying, allowing for more efficient handling of large YAML files. This feature reduces memory consumption and improves performance when working with extensive data.

  • yamljs:

    yamljs does not support streaming. It reads and writes YAML data in a single operation, which may lead to high memory usage with large files.

Custom Tags

  • js-yaml:

    js-yaml supports custom tags, allowing developers to define their own data types and serialization methods. This feature provides flexibility for handling non-standard YAML structures.

  • yaml:

    yaml also supports custom tags and offers more advanced features, including better handling of tag resolution and serialization. It allows for more complex and flexible implementations of custom data types.

  • yamljs:

    yamljs supports custom tags but with limited functionality compared to js-yaml and yaml. It allows for basic customization of how certain data types are handled during parsing and stringifying.

Error Handling

  • js-yaml:

    js-yaml provides basic error handling for parsing and stringifying operations, including informative error messages for syntax errors and invalid data.

  • yaml:

    yaml offers more robust error handling, including support for asynchronous parsing and detailed error reporting. It is designed to handle errors more gracefully, especially in complex YAML structures.

  • yamljs:

    yamljs provides simple error handling for parsing errors but is less comprehensive than js-yaml and yaml. It may not provide detailed error messages for all types of parsing issues.

Ease of Use: Code Examples

  • js-yaml:

    js-yaml Example

    const yaml = require('js-yaml');
    const fs = require('fs');
    
    // Parse YAML
    const doc = yaml.load(fs.readFileSync('file.yaml', 'utf8'));
    console.log(doc);
    
    // Stringify YAML
    const yamlStr = yaml.dump(doc);
    console.log(yamlStr);
    
  • yaml:

    yaml Example

    const { parse, stringify } = require('yaml');
    const fs = require('fs');
    
    // Parse YAML
    const doc = parse(fs.readFileSync('file.yaml', 'utf8'));
    console.log(doc);
    
    // Stringify YAML
    const yamlStr = stringify(doc);
    console.log(yamlStr);
    
  • yamljs:

    yamljs Example

    const YAML = require('yamljs');
    
    // Parse YAML
    const doc = YAML.load('file.yaml');
    console.log(doc);
    
    // Stringify YAML
    const yamlStr = YAML.stringify(doc);
    console.log(yamlStr);
    

How to Choose: js-yaml vs yaml vs yamljs

  • js-yaml:

    Choose js-yaml if you need a reliable, well-established library for parsing and dumping YAML with good performance and compatibility. It is suitable for most use cases and has a simple API.

  • yaml:

    Choose yaml if you want a modern, feature-rich library that supports advanced YAML features, streaming, and custom serialization. It is ideal for projects that require more flexibility and performance optimizations.

  • yamljs:

    Choose yamljs if you prefer a lightweight library with a simple API for quick YAML parsing and stringifying tasks. It is great for smaller projects or when you need a straightforward solution without many dependencies.

README for js-yaml

JS-YAML - YAML 1.2 parser / writer for JavaScript

CI NPM version

Online Demo

A fast and complete YAML parser and writer for JavaScript. Supports both the 1.2 and 1.1 specs, and passes the entire YAML Test Suite.

Installation

npm install js-yaml

Upgrading from v4? See the v5 migration guide.

API

Here we cover the most useful methods. If you need advanced details (such as creating your own tags), see the examples for more info.

import { load } from 'js-yaml'
import { readFileSync } from 'node:fs'

// Get document, or throw exception on error
try {
  const doc = load(readFileSync('example.yml', 'utf8'))
  console.log(doc)
} catch (e) {
  console.log(e)
}

load (string [ , options ])

Parses string as a single YAML document. Throws YAMLException on error. This function does not understand multi-document or empty sources; it throws an exception on those.

[!WARNING] When processing untrusted input, see the security considerations.

options:

  • filename (default: null) - string to be used as a file path in error/warning messages.
  • schema (default: CORE_SCHEMA) - specifies a schema to use.
    • FAILSAFE_SCHEMA - only strings, arrays and plain objects.
    • JSON_SCHEMA - all JSON-supported types.
    • CORE_SCHEMA - a superset of JSON_SCHEMA, accepting more notations for the same types.
    • YAML11_SCHEMA - adds the legacy YAML 1.1 types (!!binary, !!timestamp, !!omap, !!pairs, !!set, merge keys <<, and the broader 1.1 scalar notations).
  • json (default: false) - compatibility with JSON.parse behaviour. If true, duplicate keys in a mapping override values rather than throwing an error.
  • maxDepth (default: 100) - limits the nesting depth for collections (does not take aliases into account).
  • maxTotalMergeKeys (default: 10000) - limits the total number of keys processed by merge (<<) across one load() / loadAll() call. Set to -1 to disable.
  • maxAliases (default: -1) - limits the number of alias nodes (*ref) per document. Set to 0 to reject all aliases, or to -1 for no limit.

[!NOTE]

The default CORE_SCHEMA comes without the !!merge tag. You can easily enable it if needed:

import { load, CORE_SCHEMA, mergeTag } from 'js-yaml'

load(data, { schema: CORE_SCHEMA.withTags(mergeTag) })

[!WARNING]

The default mapTag is {}-object based and does not allow complex keys (objects, arrays and so on). That's an intentional choice for convenience. Also, non-string scalar keys, such as null, numbers or booleans, are converted to strings.

In the rare cases where you really need complex keys, use realMapTag in the schema instead. It stores any key exactly as provided, at the cost of less convenient access.

See examples for advanced customization approaches.

loadAll (string [, options ])

Same as load(), but understands multi-document sources. Returns an array of documents.

import { loadAll } from 'js-yaml'

console.log(loadAll(data))

dump (object [ , options ])

Serializes object as a YAML document. By default it can dump every supported YAML type, so it throws an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the skipInvalid option to true.

options:

  • indent (default: 2) - indentation width to use (in spaces).
  • flowLevel (default: -1) - nesting level at which collections switch from block to flow style (-1 means never).
  • seqNoIndent (default: false) - when true, does not add an indentation level to array elements, ␣␣- 1 => - 1.
  • seqInlineFirst (default: true) - when true, allows a nested collection to start on the same line after -, -\n - 1 => - - 1.
  • skipInvalid (default: false) - do not throw on invalid types (such as a function in the schema). Invalid mapping pairs and sequence items are skipped; undefined sequence items are serialized as null.
  • schema (default: a YAML11_SCHEMA-based schema) - specifies a schema to use.
  • sortKeys (default: false) - if true, sort keys when dumping YAML. If a function, use the function to sort the keys.
  • lineWidth (default: 80) - sets the max line width. Set -1 for unlimited width.
  • noRefs (default: false) - if true, don't convert duplicate objects into references; inline them instead.
  • quoteStyle (single or double, default: single) - quoting style to use when a string needs quotes.
  • forceQuotes (default: false) - if true, quote all non-key strings, using quoteStyle.
  • flowBracketPadding (default: false) - add spaces inside flow collection brackets, {a: 1} => { a: 1 }.
  • flowSkipCommaSpace (default: false) - omit the space after commas in flow collections, [1, 2] => [1,2].
  • flowSkipColonSpace (default: false) - omit the space after : in flow mappings, {a: 1} => {a:1}.
  • quoteFlowKeys (default: false) - quote flow mapping keys, {a: 1} => {"a": 1}.
  • tagBeforeAnchor (default: false) - print an explicit tag before an anchor, &ref_0 !!set => !!set &ref_0.
  • transform - a function (documents: Document[]) => void that can mutate the generated AST before it is rendered.

See examples for advanced customization approaches.

Supported YAML types

The list of standard YAML tags and corresponding JavaScript types. See also YAML tag discussion and YAML types repository.

!!null ''                   # null
!!bool 'true'               # bool
!!int '3...'                # number
!!float '3.14...'           # number
!!str '...'                 # string
!!seq [ ... ]               # array
!!map { ... }               # object (or Map)

The types below are only available in YAML11_SCHEMA (not in the default CORE_SCHEMA):

!!binary '...base64...'     # Uint8Array
!!timestamp 'YYYY-...'      # date
!!set { ... }               # Set

# Legacy YAML 1.1 compatibility only; these types cannot be dumped.
!!omap [ ... ]              # array of key-value pairs
!!pairs [ ... ]             # array of array pairs

To preserve complex keys in the first position of a !!pairs item, replace the default object-based map with realMapTag in the schema.

JavaScript-specific tags

See js-yaml-js-types for extra types.

CLI

This can be useful sometimes for a quick check.

npx js-yaml -h

Note: the CLI script comes with minimal options, and there are no big plans to extend it.