4.3 KiB
YAML
yaml
is a JavaScript parser and stringifier for YAML, a human friendly data serialization standard. It supports both parsing and stringifying data using all versions of YAML, along with all common data schemas. As a particularly distinguishing feature, yaml
fully supports reading and writing comments and blank lines in YAML documents.
The library is released under the ISC open source license, and the code is available on GitHub. It runs on Node.js 6 and later with no external dependencies, and in browsers from IE 11 upwards (Note: @babel/runtime
is used only by the "browser"
entry point).
For more information, see the project's documentation site: eemeli.org/yaml
To install:
npm install yaml
# or
yarn add yaml
Note: yaml
0.x and 1.x are rather different implementations. For the earlier yaml
, see tj/js-yaml.
API Overview
The API provided by yaml
has three layers, depending on how deep you need to go: Parse & Stringify, Documents, and the CST Parser. The first has the simplest API and "just works", the second gets you all the bells and whistles supported by the library along with a decent AST, and the third is the closest to YAML source, making it fast, raw, and crude.
import YAML from 'yaml'
// or
const YAML = require('yaml')
Parse & Stringify
YAML Documents
YAML.createNode(value, wrapScalars, tag): Node
YAML.defaultOptions
YAML.Document
YAML.parseAllDocuments(str, options): YAML.Document[]
YAML.parseDocument(str, options): YAML.Document
import { Pair, YAMLMap, YAMLSeq } from 'yaml/types'
CST Parser
import parseCST from 'yaml/parse-cst'
YAML.parse
# file.yml
YAML:
- A human-readable data serialization language
- https://en.wikipedia.org/wiki/YAML
yaml:
- A complete JavaScript implementation
- https://www.npmjs.com/package/yaml
import fs from 'fs'
import YAML from 'yaml'
YAML.parse('3.14159')
// 3.14159
YAML.parse('[ true, false, maybe, null ]\n')
// [ true, false, 'maybe', null ]
const file = fs.readFileSync('./file.yml', 'utf8')
YAML.parse(file)
// { YAML:
// [ 'A human-readable data serialization language',
// 'https://en.wikipedia.org/wiki/YAML' ],
// yaml:
// [ 'A complete JavaScript implementation',
// 'https://www.npmjs.com/package/yaml' ] }
YAML.stringify
import YAML from 'yaml'
YAML.stringify(3.14159)
// '3.14159\n'
YAML.stringify([true, false, 'maybe', null])
// `- true
// - false
// - maybe
// - null
// `
YAML.stringify({ number: 3, plain: 'string', block: 'two\nlines\n' })
// `number: 3
// plain: string
// block: >
// two
//
// lines
// `
Browser testing provided by: