YAML 1.2 Parser and Serializer for JavaScript

4.1.1 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load YAML from a file using `safeLoad` and serialize a JavaScript object to YAML using `safeDump`, emphasizing safe practices.

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);
  }
}

view raw JSON →