租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

246 lines
8.3 KiB

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