YAML 1.2 Parser and Serializer for JavaScript
JS-YAML is a high-performance JavaScript library for parsing and serializing YAML 1.2 documents. Originally inspired by PyYAML, it underwent a complete rewrite to optimize for speed and full adherence to the latest YAML specification. The current stable version, 4.1.1, offers robust functionalities including both 'safe' and 'full' modes for loading and dumping YAML data, catering to various security and feature requirements. It maintains a regular release cadence for bug fixes and minor improvements, with major versions introducing significant API or feature changes. Key differentiators include its speed, comprehensive support for YAML 1.2 tags, and a strong emphasis on providing a secure parsing option via `safeLoad`, which limits potentially unsafe features like arbitrary code execution. While primarily used in Node.js, it also provides a browser-compatible build, though its browser support is explicitly noted as less thoroughly tested and may require additional shims for older environments.
Common errors
-
YAMLException: bad indentation of a mapping entry (line X, column Y)
cause The YAML document has incorrect indentation, which is critical for YAML's structure.fixCarefully review the YAML content, specifically around the indicated line and column, for consistent spacing and proper nesting. YAML uses spaces, not tabs, for indentation. -
Error: Cannot find module 'js-yaml'
cause The 'js-yaml' package is not installed in the project or the import path is incorrect.fixEnsure the package is installed by running `npm install js-yaml` or `yarn add js-yaml`. Verify that the import statement correctly references the package name, e.g., `const yaml = require('js-yaml');` or `import { safeLoad } from 'js-yaml';`. -
TypeError: Cannot read properties of undefined (reading 'someProperty')
cause Attempting to access a property on an object that was parsed as `undefined` or `null` from the YAML document.fixImplement defensive programming by checking for `null` or `undefined` values before accessing properties, especially for optional YAML fields. Use optional chaining (`?.`) or nullish coalescing (`??`) if your environment supports it.
Warnings
- breaking Duplicate keys in YAML mappings now throw an error by default.
- gotcha Using `yaml.load()` or `yaml.dump()` can introduce security vulnerabilities or produce non-standard output with untrusted input.
- gotcha Limited and less tested browser support for `js-yaml`.
- gotcha The `!!js/function` tag requires `esprima` for proper parsing in browsers and is a security risk.
Install
-
npm install js-yaml -
yarn add js-yaml -
pnpm add js-yaml
Imports
- yaml
import * as yaml from 'js-yaml';
const yaml = require('js-yaml'); - safeLoad
import { safeLoad } from 'js-yaml'; - safeDump
import { safeDump } from 'js-yaml';
Quickstart
const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');
// Example YAML content to parse
const yamlContent = `
greeting: hello
name: world
version: 1.0
config:
enabled: true
port: 3000
data:
- item1
- item2
`;
// Create a dummy YAML file for demonstration purposes
const tempFilePath = path.join(__dirname, 'example.yml');
fs.writeFileSync(tempFilePath, yamlContent, 'utf8');
try {
// Use safeLoad to parse the YAML content from the dummy file
const doc = yaml.safeLoad(fs.readFileSync(tempFilePath, 'utf8'));
console.log('Successfully loaded YAML document:');
console.log(JSON.stringify(doc, null, 2));
// Example of dumping a JavaScript object back into YAML format
const dataToDump = {
title: 'My Document',
author: 'AI Agent',
date: new Date().toISOString().split('T')[0] // Format date for YAML
};
const dumpedYaml = yaml.safeDump(dataToDump); // safeDump is also preferred for output
console.log('\nSuccessfully dumped object to YAML:');
console.log(dumpedYaml);
} catch (e) {
console.error('Error processing YAML:', e.message);
} finally {
// Clean up the dummy file after use
if (fs.existsSync(tempFilePath)) {
fs.unlinkSync(tempFilePath);
}
}