Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

yaml-parser

floby1.5kMIT3.5.3

YAML 1.2 parser and serializer

yaml, parser, serializer, pyyaml

readme

YAML-PARSER - YAML 1.2 parser / writer for JavaScript

Build Status NPM version

Online Demo

yaml-parser is a fork of js-yaml whose goal is to remove command-line functionalities in order to provide a leaner module.

This is an implementation of YAML, a human friendly data serialization language. Started as PyYAML port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.

Installation

YAML module for node.js

npm install --save js-yaml

API

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

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

// Get document, or throw exception on error
try {
  var doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
  console.log(doc);
} catch (e) {
  console.log(e);
}

safeLoad (string [ , options ])

Recommended loading way. Parses string as single YAML document. Returns a JavaScript object or throws YAMLException on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data.

options:

  • filename (default: null) - string to be used as a file path in error/warning messages.
  • onWarning (default: null) - function to call on warning messages. Loader will throw on warnings if this function is not provided.
  • schema (default: `DEFAULTSAFE_SCHEMA`)_ - specifies a schema to use.
  • json (default: false) - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error.

NOTE: This function does not understand multi-document sources, it throws exception on those.

NOTE: JS-YAML does not support schema-specific tag resolution restrictions. So, JSON schema is not as strict as defined in the YAML specification. It allows numbers in any notation, use Null and NULL as null, etc. Core schema also has no such restrictions. It allows binary notation for integers.

load (string [ , options ])

Use with care with untrusted sources. The same as safeLoad() but uses DEFAULT_FULL_SCHEMA by default - adds some JavaScript-specific types: !!js/function, !!js/regexp and !!js/undefined. For untrusted sources you must additionally validate object structure, to avoid injections:

var untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"';

// I'm just converting that string, what could possibly go wrong?
require('js-yaml').load(untrusted_code) + ''

safeLoadAll (string, iterator [ , options ])

Same as safeLoad(), but understands multi-document sources and apply iterator to each document.

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

yaml.safeLoadAll(data, function (doc) {
  console.log(doc);
});

loadAll (string, iterator [ , options ])

Same as safeLoadAll() but uses DEFAULT_FULL_SCHEMA by default.

safeDump (object [ , options ])

Serializes object as YAML document. Uses DEFAULT_SAFE_SCHEMA, so it will throw exception if you try to dump regexps or functions. However, you can disable exceptions by skipInvalid option.

options:

  • indent (default: 2) - indentation width to use (in spaces).
  • skipInvalid (default: false) - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types.
  • flowLevel (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere
  • styles - "tag" => "style" map. Each tag may have own set of styles.
  • schema (default: `DEFAULTSAFE_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) - set max line width.
  • noRefs (default: false) - if true, don't convert duplicate objects into references

styles:

!!null
  "canonical"   => "~"

!!int
  "binary"      => "0b1", "0b101010", "0b1110001111010"
  "octal"       => "01", "052", "016172"
  "decimal"     => "1", "42", "7290"
  "hexadecimal" => "0x1", "0x2A", "0x1C7A"

!!null, !!bool, !!float
  "lowercase"   => "null", "true", "false", ".nan", '.inf'
  "uppercase"   => "NULL", "TRUE", "FALSE", ".NAN", '.INF'
  "camelcase"   => "Null", "True", "False", ".NaN", '.Inf'

By default, !!int uses decimal, and !!null, !!bool, !!float use lowercase.

dump (object [ , options ])

Same as safeDump() but without limits (uses DEFAULT_FULL_SCHEMA by default).

Supported YAML types

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

!!null ''                   # null
!!bool 'yes'                # bool
!!int '3...'                # number
!!float '3.14...'           # number
!!binary '...base64...'     # buffer
!!timestamp 'YYYY-...'      # date
!!omap [ ... ]              # array of key-value pairs
!!pairs [ ... ]             # array or array pairs
!!set { ... }               # array of objects with given keys and null values
!!str '...'                 # string
!!seq [ ... ]               # array
!!map { ... }               # object

JavaScript-specific tags

!!js/regexp /pattern/gim            # RegExp
!!js/undefined ''                   # Undefined
!!js/function 'function () {...}'   # Function

Caveats

Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or array as keys, and stringifies (by calling .toString method) them at the moment of adding them.

---
? [ foo, bar ]
: - baz
? { foo: bar }
: - baz
  - baz
{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }

Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded.

&anchor foo:
  foo: bar
  *anchor: duplicate key
  baz: bat
  *anchor: duplicate key

Breaking changes in 2.x.x -> 3.x.x

If you have not used custom tags or loader classes and not loaded yaml files via require() - no changes needed. Just upgrade library.

Otherwise, you should:

  1. Replace all occurences of require('xxxx.yml') by fs.readFileSync() + yaml.safeLoad().
  2. rewrite your custom tags constructors and custom loader classes, to conform new API. See examples and wiki for details.

License

View the LICENSE file (MIT).

changelog

3.5.2 / 2016-01-11

  • Maintenance: missed comma in bower config.

3.5.1 / 2016-01-11

  • Removed inherit dependency, #239.
  • Better browserify workaround for esprima load.
  • Demo rewrite.

3.5.0 / 2016-01-10

  • Dumper. Fold strings only, #217.
  • Dumper. norefs option, to clone linked objects, #229.
  • Loader. Throw a warning for duplicate keys, #166.
  • Improved browserify support (mark esprima & Buffer excluded).

3.4.6 / 2015-11-26

  • Use standalone inherit to keep browserified files clear.

3.4.5 / 2015-11-23

  • Added lineWidth option to dumper.

3.4.4 / 2015-11-21

  • Fixed floats dump (missed dot for scientific format), #220.
  • Allow non-printable characters inside quoted scalars, #192.

3.4.3 / 2015-10-10

  • Maintenance release - deps bump (esprima, argparse).

3.4.2 / 2015-09-09

  • Fixed serialization of duplicated entries in sequences, #205. Thanks to @vogelsgesang.

3.4.1 / 2015-09-05

  • Fixed stacktrace handling in generated errors, for browsers (FF/IE).

3.4.0 / 2015-08-23

  • Fixed multiline keys dump, #197. Thanks to @tcr.
  • Don't throw on warnongs anymore. Use onWarning option to catch.
  • Throw error on unknown tags (was warning before).
  • Fixed heading line breaks in some scalars (regression).
  • Reworked internals of error class.

3.3.1 / 2015-05-13

  • Added .sortKeys dumper option, thanks to @rjmunro.
  • Fixed astral characters support, #191.

3.3.0 / 2015-04-26

  • Significantly improved long strings formatting in dumper, thanks to @isaacs.
  • Strip BOM if exists.

3.2.7 / 2015-02-19

  • Maintenance release.
  • Updated dependencies.
  • HISTORY.md -> CHANGELOG.md

3.2.6 / 2015-02-07

  • Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE).
  • Fixed demo dates dump (#113, thanks to @Hypercubed).

3.2.5 / 2014-12-28

  • Fixed resolving of all built-in types on empty nodes.
  • Fixed invalid warning on empty lines within quoted scalars and flow collections.
  • Fixed bug: Tag on an empty node didn't resolve in some cases.

3.2.4 / 2014-12-19

  • Fixed resolving of !!null tag on an empty node.

3.2.3 / 2014-11-08

  • Implemented dumping of objects with circular and cross references.
  • Partially fixed aliasing of constructed objects. (see issue #141 for details)

3.2.2 / 2014-09-07

  • Fixed infinite loop on unindented block scalars.
  • Rewritten base64 encode/decode in binary type, to keep code licence clear.

3.2.1 / 2014-08-24

  • Nothig new. Just fix npm publish error.

3.2.0 / 2014-08-24

  • Added input piping support to CLI.
  • Fixed typo, that could cause hand on initial indent (#139).

3.1.0 / 2014-07-07

  • 1.5x-2x speed boost.
  • Removed deprecated require('xxx.yml') support.
  • Significant code cleanup and refactoring.
  • Internal API changed. If you used custom types - see updated examples. Others are not affected.
  • Even if the input string has no trailing line break character, it will be parsed as if it has one.
  • Added benchmark scripts.
  • Moved bower files to /dist folder
  • Bugfixes.

3.0.2 / 2014-02-27

  • Fixed bug: "constructor" string parsed as null.

3.0.1 / 2013-12-22

  • Fixed parsing of literal scalars. (issue #108)
  • Prevented adding unnecessary spaces in object dumps. (issue #68)
  • Fixed dumping of objects with very long (> 1024 in length) keys.

3.0.0 / 2013-12-16

  • Refactored code. Changed API for custom types.
  • Removed output colors in CLI, dump json by default.
  • Removed big dependencies from browser version (esprima, buffer)
    • load esprima manually, if !!js/function needed
    • !!bin now returns Array in browser
  • AMD support.
  • Don't quote dumped strings because of - & ? (if not first char).
  • Deprecated loading yaml files via require(), as not recommended behaviour for node.

2.1.3 / 2013-10-16

  • Fix wrong loading of empty block scalars.

2.1.2 / 2013-10-07

  • Fix unwanted line breaks in folded scalars.

2.1.1 / 2013-10-02

  • Dumper now respects deprecated booleans syntax from YAML 1.0/1.1
  • Fixed reader bug in JSON-like sequences/mappings.

2.1.0 / 2013-06-05

  • Add standard YAML schemas: Failsafe (FAILSAFE_SCHEMA), JSON (JSON_SCHEMA) and Core (CORE_SCHEMA).
  • Rename DEFAULT_SCHEMA to DEFAULT_FULL_SCHEMA and SAFE_SCHEMA to DEFAULT_SAFE_SCHEMA.
  • Bug fix: export NIL constant from the public interface.
  • Add skipInvalid dumper option.
  • Use safeLoad for require extension.

2.0.5 / 2013-04-26

  • Close security issue in !!js/function constructor. Big thanks to @nealpoole for security audit.

2.0.4 / 2013-04-08

  • Updated .npmignore to reduce package size

2.0.3 / 2013-02-26

  • Fixed dumping of empty arrays ans objects. ([] and {} instead of null)

2.0.2 / 2013-02-15

  • Fixed input validation: tabs are printable characters.

2.0.1 / 2013-02-09

  • Fixed error, when options not passed to function cass

2.0.0 / 2013-02-09

  • Full rewrite. New architecture. Fast one-stage parsing.
  • Changed custom types API.
  • Added YAML dumper.

1.0.3 / 2012-11-05

  • Fixed utf-8 files loading.

1.0.2 / 2012-08-02

  • Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44.
  • Fix timstamps incorectly parsed in local time when no time part specified.

1.0.1 / 2012-07-07

  • Fixes TypeError: 'undefined' is not an object under Safari. Thanks Phuong.
  • Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46.

1.0.0 / 2012-07-01

  • y, yes, n, no, on, off are not converted to Booleans anymore. Fixes #42.
  • require(filename) now returns a single document and throws an Error if file contains more than one document.
  • CLI was merged back from js-yaml.bin

0.3.7 / 2012-02-28

  • Fix export of addConstructor(). Closes #39.

0.3.6 / 2012-02-22

  • Removed AMD parts - too buggy to use. Need help to rewrite from scratch
  • Removed YUI compressor warning (renamed double variable). Closes #40.

0.3.5 / 2012-01-10

  • Workagound for .npmignore fuckup under windows. Thanks to airportyh.

0.3.4 / 2011-12-24

  • Fixes str[] for oldIEs support.
  • Adds better has change support for browserified demo.
  • improves compact output of Error. Closes #33.

0.3.3 / 2011-12-20

  • jsyaml executable moved to separate module.
  • adds compact stringification of Errors.

0.3.2 / 2011-12-16

  • Fixes ug with block style scalars. Closes #26.
  • All sources are passing JSLint now.
  • Fixes bug in Safari. Closes #28.
  • Fixes bug in Opers. Closes #29.
  • Improves browser support. Closes #20.
  • Added jsyaml executable.
  • Added !!js/function support. Closes #12.

0.3.1 / 2011-11-18

  • Added AMD support for browserified version.
  • Wrapped browserified js-yaml into closure.
  • Fixed the resolvement of non-specific tags. Closes #17.
  • Added permalinks for online demo YAML snippets. Now we have YPaste service, lol.
  • Added !!js/regexp and !!js/undefined types. Partially solves #12.
  • Fixed !!set mapping.
  • Fixed month parse in dates. Closes #19.

0.3.0 / 2011-11-09

  • Removed JS.Class dependency. Closes #3.
  • Added browserified version. Closes #13.
  • Added live demo of browserified version.
  • Ported some of the PyYAML tests. See #14.
  • Fixed timestamp bug when fraction was given.

0.2.2 / 2011-11-06

  • Fixed crash on docs without ---. Closes #8.
  • Fixed miltiline string parse
  • Fixed tests/comments for using array as key

0.2.1 / 2011-11-02

  • Fixed short file read (<4k). Closes #9.

0.2.0 / 2011-11-02

  • First public release