Skip to content
Permalink
Newer
Older
100644 246 lines (185 sloc) 8.27 KB
Ignoring revisions in .git-blame-ignore-revs.
1
JS-YAML - YAML 1.2 parser / writer for JavaScript
2
=================================================
3
July 27, 2021 19:01
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
10
This is an implementation of [YAML](http://yaml.org/), a human-friendly data
11
serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was
12
completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.
13
14
15
Installation
16
------------
17
18
### YAML module for node.js
19
20
```
21
npm install js-yaml
22
```
23
24
25
### CLI executable
26
27
If you want to inspect your YAML files from CLI, install js-yaml globally:
28
29
```
30
npm install -g js-yaml
31
```
32
33
#### Usage
34
35
```
36
usage: js-yaml [-h] [-v] [-c] [-t] file
37
38
Positional arguments:
39
file File with YAML document(s)
40
41
Optional 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
49
API
50
---
51
52
Here we cover the most 'useful' methods. If you need advanced details (creating
July 27, 2021 19:01
53
your own tags), see [examples](https://github.com/nodeca/js-yaml/tree/master/examples)
54
for more info.
55
56
``` javascript
July 27, 2021 19:01
57
const yaml = require('js-yaml');
58
const fs = require('fs');
59
60
// Get document, or throw exception on error
61
try {
July 27, 2021 19:01
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
July 27, 2021 19:01
70
### load (string [ , options ])
July 27, 2021 19:01
72
Parses `string` as single YAML document. Returns either a
73
plain object, a string, a number, `null` or `undefined`, or throws `YAMLException` on error. By default, does
74
not support regexps, functions and undefined.
75
76
options:
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.
July 27, 2021 19:01
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
July 27, 2021 19:01
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
92
NOTE: This function **does not** understand multi-document sources, it throws
93
exception on those.
94
95
NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions.
96
So, the JSON schema is not as strictly defined in the YAML specification.
97
It allows numbers in any notation, use `Null` and `NULL` as `null`, etc.
98
The core schema also has no such restrictions. It allows binary notation for integers.
99
100
July 27, 2021 19:01
101
### loadAll (string [, iterator] [, options ])
July 27, 2021 19:01
103
Same as `load()`, but understands multi-document sources. Applies
104
`iterator` to each document if specified, or returns array of documents.
105
106
``` javascript
July 27, 2021 19:01
107
const yaml = require('js-yaml');
July 27, 2021 19:01
109
yaml.loadAll(data, function (doc) {
110
console.log(doc);
111
});
112
```
113
114
July 27, 2021 19:01
115
### dump (object [ , options ])
July 27, 2021 19:01
117
Serializes `object` as a YAML document. Uses `DEFAULT_SCHEMA`, so it will
118
throw an exception if you try to dump regexps or functions. However, you can
119
disable exceptions by setting the `skipInvalid` option to `true`.
120
121
options:
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.
July 27, 2021 19:01
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.
July 27, 2021 19:01
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.
July 27, 2021 19:01
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.
July 27, 2021 19:01
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
142
The following table show availlable styles (e.g. "canonical",
143
"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml
144
output 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"
July 27, 2021 19:01
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
170
Example:
171
172
``` javascript
July 27, 2021 19:01
173
dump(object, {
174
'styles': {
175
'!!null': 'canonical' // dump null as ~
176
},
177
'sortKeys': true // sort object keys
178
});
179
```
180
181
Supported YAML types
182
--------------------
183
July 27, 2021 19:01
184
The 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
July 27, 2021 19:01
205
See [js-yaml-js-types](https://github.com/nodeca/js-yaml-js-types) for
206
extra types.
207
208
209
Caveats
210
-------
211
212
Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects
213
or arrays as keys, and stringifies (by calling `toString()` method) them at the
214
moment 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
229
Also, reading of properties on implicit block mapping keys is not supported yet.
230
So, 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
July 27, 2021 19:01
241
js-yaml for enterprise
242
----------------------
July 27, 2021 19:01
244
Available as part of the Tidelift Subscription
July 27, 2021 19:01
246
The 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)