YAML Parser and Stringifier
The `yaml` library is a robust and definitive JavaScript parser and stringifier for YAML, supporting both YAML 1.1 and 1.2 specifications and all common data schemas. It currently maintains a stable version 2.8.3, with an active release cadence that regularly introduces new features and bug fixes. A v3.0.0-0 prerelease is also available under the `next` tag, though it is not yet stable for production use and is not recommended for production environments. Key differentiators include passing all `yaml-test-suite` tests, its ability to parse any string input without throwing errors (extracting as much YAML as possible), and comprehensive support for parsing, modifying, and writing YAML comments and blank lines. It boasts no external dependencies and runs across various JavaScript environments including Node.js (requiring `>= 14.6`), modern browsers, Deno, Bun, and Cloudflare Workers, shipping with full TypeScript type definitions (minimum TS 3.9).
Common errors
-
ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` syntax in an ECMAScript Module (ESM) environment (e.g., `"type": "module"` in `package.json` or `.mjs` files).fixUpdate imports to use ESM syntax: `import { parse, stringify } from 'yaml'`. -
Property 'parse' does not exist on type 'typeof import("yaml")' or 'yaml.parse is not a function'cause Incorrectly importing named exports, often by trying to use a default import or a CommonJS-style property access with ESM.fixEnsure you are using named imports: `import { parse, stringify } from 'yaml'`. -
Error: The current Node.js version is <some-version> which does not satisfy the requirement >= 14.6.
cause Running the library on an unsupported Node.js version.fixUpdate your Node.js environment to a version `>= 14.6` or higher to meet the package's engine requirements.
Warnings
- breaking Version 3.0.0-0 is a prerelease and highly unstable. It's published under the `next` dist-tag and using a non-exact range like `^3.0.0-0` can cause unpredictable breaking changes when new prereleases are published.
- breaking Node.js engine requirement shifted in `v2.7.0` to `>= 14.18` from `>= 14.6`, then reverted to `>= 14.6` in `v2.8.0`. Ensure your Node.js environment meets the specific requirement for the minor version of `yaml` you are using to avoid runtime errors.
- gotcha The minimum supported TypeScript version for the included typings is 3.9. Using the library with earlier TypeScript versions may result in type errors.
- gotcha While documented endpoints are semver-major, undocumented library internals may change between minor versions. Relying on internal structures not explicitly part of the public API can lead to unexpected breakages.
Install
-
npm install yaml -
yarn add yaml -
pnpm add yaml
Imports
- parse
const parse = require('yaml').parseimport { parse } from 'yaml' - stringify
const stringify = require('yaml').stringifyimport { stringify } from 'yaml' - Document
const Document = require('yaml').Documentimport { Document } from 'yaml' - parseDocument
const parseDocument = require('yaml').parseDocumentimport { parseDocument } from 'yaml' - YAMLMap, YAMLSeq, Scalar
const { YAMLMap } = require('yaml')import { YAMLMap, YAMLSeq, Scalar } from 'yaml'
Quickstart
import { parse, stringify, Document, YAMLMap, Scalar } from 'yaml';
const yamlString = `
# My shopping list
- item: Apples
quantity: 2
notes: Green ones
---
# My second shopping list
- item: Milk
quantity: 1
unit: gallon
`;
// Parse a multi-document YAML string, keeping CST nodes for better comment preservation
const documents = parse(yamlString, { keepCstNodes: true }) as Document[];
// Access and modify the first document
const firstDoc = documents[0];
if (firstDoc && firstDoc.contents instanceof Array) { // Assuming a sequence at root
const appleItem = firstDoc.contents[0];
if (appleItem instanceof YAMLMap) {
appleItem.set('quantity', 3); // Change quantity
appleItem.set('notes', 'Honeycrisp preferred'); // Update notes
}
}
// Access and modify the second document
const secondDoc = documents[1];
if (secondDoc && secondDoc.contents instanceof Array) {
secondDoc.contents.push(new YAMLMap());
const newItem = secondDoc.contents[secondDoc.contents.length - 1] as YAMLMap;
newItem.set('item', 'Bread');
newItem.set('quantity', 1);
newItem.set('type', 'whole wheat');
}
// Stringify the modified documents back to YAML
const modifiedYaml = documents.map(doc => stringify(doc)).join('\n---\n');
console.log('Original YAML:\n', yamlString);
console.log('\nModified YAML:\n', modifiedYaml);
// Example of parsing a single document with parseDocument and accessing AST
const singleDocString = `
user: John Doe
roles:
- admin
- editor
active: true
`;
const doc = parseDocument(singleDocString);
if (doc.contents instanceof YAMLMap) {
const userNode = doc.contents.get('user');
if (userNode instanceof Scalar) {
console.log(`\nUser from single document: ${userNode.value}`);
}
doc.contents.set('status', 'online');
}
console.log('\nModified Single Document with new status:\n', doc.toString());