UNPKG

8.47 kBMarkdownView Raw
1JS-YAML - YAML 1.2 parser / writer for JavaScript
2=================================================
3
4[![CI](https://github.com/nodeca/js-yaml/workflows/CI/badge.svg?branch=master)](https://github.com/nodeca/js-yaml/actions)
5[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml)
6
7__[Online Demo](http://nodeca.github.com/js-yaml/)__
8
9
10This is an implementation of [YAML](http://yaml.org/), a human-friendly data
11serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was
12completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.
13
14
15Installation
16------------
17
18### YAML module for node.js
19
20```
21npm install js-yaml
22```
23
24
25### CLI executable
26
27If you want to inspect your YAML files from CLI, install js-yaml globally:
28
29```
30npm install -g js-yaml
31```
32
33#### Usage
34
35```
36usage: js-yaml [-h] [-v] [-c] [-t] file
37
38Positional arguments:
39 file File with YAML document(s)
40
41Optional arguments:
42 -h, --help Show this help message and exit.
43 -v, --version Show program's version number and exit.
44 -c, --compact Display errors in compact mode
45 -t, --trace Show stack trace on error
46```
47
48
49API
50---
51
52Here we cover the most 'useful' methods. If you need advanced details (creating
53your own tags), see [examples](https://github.com/nodeca/js-yaml/tree/master/examples)
54for more info.
55
56``` javascript
57const yaml = require('js-yaml');
58const fs = require('fs');
59
60// Get document, or throw exception on error
61try {
62 const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
63 console.log(doc);
64} catch (e) {
65 console.log(e);
66}
67```
68
69
70### load (string [ , options ])
71
72Parses `string` as single YAML document. Returns either a
73plain object, a string, a number, `null` or `undefined`, or throws `YAMLException` on error. By default, does
74not support regexps, functions and undefined.
75
76options:
77
78- `filename` _(default: null)_ - string to be used as a file path in
79 error/warning messages.
80- `onWarning` _(default: null)_ - function to call on warning messages.
81 Loader will call this function with an instance of `YAMLException` for each warning.
82- `schema` _(default: `DEFAULT_SCHEMA`)_ - specifies a schema to use.
83 - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects:
84 http://www.yaml.org/spec/1.2/spec.html#id2802346
85 - `JSON_SCHEMA` - all JSON-supported types:
86 http://www.yaml.org/spec/1.2/spec.html#id2803231
87 - `CORE_SCHEMA` - same as `JSON_SCHEMA`:
88 http://www.yaml.org/spec/1.2/spec.html#id2804923
89 - `DEFAULT_SCHEMA` - all supported YAML types.
90- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error.
91
92NOTE: This function **does not** understand multi-document sources, it throws
93exception on those.
94
95NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions.
96So, the JSON schema is not as strictly defined in the YAML specification.
97It allows numbers in any notation, use `Null` and `NULL` as `null`, etc.
98The core schema also has no such restrictions. It allows binary notation for integers.
99
100
101### loadAll (string [, iterator] [, options ])
102
103Same as `load()`, but understands multi-document sources. Applies
104`iterator` to each document if specified, or returns array of documents.
105
106``` javascript
107const yaml = require('js-yaml');
108
109yaml.loadAll(data, function (doc) {
110 console.log(doc);
111});
112```
113
114
115### dump (object [ , options ])
116
117Serializes `object` as a YAML document. Uses `DEFAULT_SCHEMA`, so it will
118throw an exception if you try to dump regexps or functions. However, you can
119disable exceptions by setting the `skipInvalid` option to `true`.
120
121options:
122
123- `indent` _(default: 2)_ - indentation width to use (in spaces).
124- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements
125- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function
126 in the safe schema) and skip pairs and single values with such types.
127- `flowLevel` _(default: -1)_ - specifies level of nesting, when to switch from
128 block to flow style for collections. -1 means block style everwhere
129- `styles` - "tag" => "style" map. Each tag may have own set of styles.
130- `schema` _(default: `DEFAULT_SCHEMA`)_ specifies a schema to use.
131- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a
132 function, use the function to sort the keys.
133- `lineWidth` _(default: `80`)_ - set max line width. Set `-1` for unlimited width.
134- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references
135- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older
136 yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1
137- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded.
138- `quotingType` _(`'` or `"`, default: `'`)_ - strings will be quoted using this quoting style. If you specify single quotes, double quotes will still be used for non-printable characters.
139- `forceQuotes` _(default: `false`)_ - if `true`, all non-key strings will be quoted even if they normally don't need to.
140- `replacer` - callback `function (key, value)` called recursively on each key/value in source object (see `replacer` docs for `JSON.stringify`).
141
142The following table show availlable styles (e.g. "canonical",
143"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml
144output is shown on the right side after `=>` (default setting) or `->`:
145
146``` none
147!!null
148 "canonical" -> "~"
149 "lowercase" => "null"
150 "uppercase" -> "NULL"
151 "camelcase" -> "Null"
152
153!!int
154 "binary" -> "0b1", "0b101010", "0b1110001111010"
155 "octal" -> "0o1", "0o52", "0o16172"
156 "decimal" => "1", "42", "7290"
157 "hexadecimal" -> "0x1", "0x2A", "0x1C7A"
158
159!!bool
160 "lowercase" => "true", "false"
161 "uppercase" -> "TRUE", "FALSE"
162 "camelcase" -> "True", "False"
163
164!!float
165 "lowercase" => ".nan", '.inf'
166 "uppercase" -> ".NAN", '.INF'
167 "camelcase" -> ".NaN", '.Inf'
168```
169
170Example:
171
172``` javascript
173dump(object, {
174 'styles': {
175 '!!null': 'canonical' // dump null as ~
176 },
177 'sortKeys': true // sort object keys
178});
179```
180
181Supported YAML types
182--------------------
183
184The list of standard YAML tags and corresponding JavaScript types. See also
185[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and
186[YAML types repository](http://yaml.org/type/).
187
188```
189!!null '' # null
190!!bool 'yes' # bool
191!!int '3...' # number
192!!float '3.14...' # number
193!!binary '...base64...' # buffer
194!!timestamp 'YYYY-...' # date
195!!omap [ ... ] # array of key-value pairs
196!!pairs [ ... ] # array or array pairs
197!!set { ... } # array of objects with given keys and null values
198!!str '...' # string
199!!seq [ ... ] # array
200!!map { ... } # object
201```
202
203**JavaScript-specific tags**
204
205See [js-yaml-js-types](https://github.com/nodeca/js-yaml-js-types) for
206extra types.
207
208
209Caveats
210-------
211
212Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects
213or arrays as keys, and stringifies (by calling `toString()` method) them at the
214moment of adding them.
215
216``` yaml
217---
218? [ foo, bar ]
219: - baz
220? { foo: bar }
221: - baz
222 - baz
223```
224
225``` javascript
226{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }
227```
228
229Also, reading of properties on implicit block mapping keys is not supported yet.
230So, the following YAML document cannot be loaded.
231
232``` yaml
233&anchor foo:
234 foo: bar
235 *anchor: duplicate key
236 baz: bat
237 *anchor: duplicate key
238```
239
240
241js-yaml for enterprise
242----------------------
243
244Available as part of the Tidelift Subscription
245
246The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)