Multi-document YAML with yaml
A single YAML file can hold several documents separated by ---, as in Kubernetes manifests; parseAllDocuments reads all of them.
How it works
- parse() expects one document. The code first passes the stream to
parseand prints the error it throws. The docs point toparseAllDocumentsfor this case. [1] - Read every document.
parseAllDocuments(str)returns an array ofDocumentobjects. The code prints how many there are and converts each to plain data withtoJS(). [1] - Write a stream. To produce a multi-document string, the code calls
stringifyonce per value and joins the results with...\n, as the docs describe. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { parse, parseAllDocuments, stringify } from 'yaml'
const stream = `kind: Deployment
name: web
replicas: 2
---
kind: Service
name: web
port: 80
---
kind: ConfigMap
name: web-config
`
try {
parse(stream)
} catch (err) {
console.log('parse() error:', err.message.split('\n')[0])
}
const docs = parseAllDocuments(stream)
console.log('documents found:', docs.length)
docs.forEach((doc, i) => console.log('doc ' + (i + 1) + ':', JSON.stringify(doc.toJS())))
// write several documents into one string
const out = [{ step: 'build' }, { step: 'test' }, { step: 'deploy' }]
.map((value) => stringify(value))
.join('...\n')
console.log('--- written stream ---')
out.trimEnd().split('\n').forEach((line) => console.log(line))
Add a fourth document to the stream and watch the count change. Code written by AgentGid [1].
Add a fourth document to the stream and watch the count change. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with yaml 2.9.1. Needs WebGL.
More yaml examples
Parse YAML in JavaScript with yaml Convert an object to YAML with yaml Parse options and schemas in yaml Edit YAML without losing comments
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.