Working with YAML in JavaScript (Node.js)
YAML (YAML Ain't Markup Language) is a human-readable data serialization format often used for configuration files (e.g., in Docker Compose, Kubernetes, Ansible). In the Node.js ecosystem, there are two main libraries for working with YAML: js-yaml (the most popular) and yaml (modern, with stream support).
In this article, we will explore both libraries, learn how to parse YAML into JavaScript objects, serialize objects back to YAML, as well as handle errors and work with files.
Installing Libraries
First, install one of the libraries via npm:
# Install js-yaml (recommended for most projects)npm install js-yaml
# Install the more modern yaml librarynpm install yamlThe js-yaml Library
js-yaml is the most mature and widely used library for working with YAML in Node.js. It supports the full YAML 1.2 specification, including complex data types, tags, and custom schemas.
Parsing a YAML String
const yaml = require('js-yaml');
const yamlString = `server: host: localhost port: 8080 ssl: truedatabase: driver: postgresql host: db.example.com port: 5432 credentials: user: admin password: secret`;
try { const data = yaml.load(yamlString); console.log(data.server.host); // "localhost" console.log(data.database.credentials.user); // "admin"} catch (e) { console.error('YAML parsing error:', e.message);}Parsing a YAML File
const fs = require('fs');const yaml = require('js-yaml');
try { const fileContents = fs.readFileSync('./config.yaml', 'utf8'); const data = yaml.load(fileContents); console.log(data);} catch (e) { console.error('File reading error:', e.message);}Serialization to YAML
const yaml = require('js-yaml');
const config = { app: { name: "MyApp", version: "1.0.0" }, features: { logging: true, cache: { ttl: 3600, type: "redis" } }};
const yamlString = yaml.dump(config, { indent: 2, // 2-space indentation lineWidth: 80, // maximum line length noRefs: true, // do not use references sortKeys: true // sort keys});
console.log(yamlString);// Output:// app:// name: MyApp// version: 1.0.0// features:// cache:// ttl: 3600// type: redis// logging: trueWorking with Custom Types
js-yaml supports custom YAML tags for handling special data types:
const yaml = require('js-yaml');
// Create a custom type for datesconst DateType = new yaml.Type('!date', { kind: 'scalar', resolve: (data) => data.match(/^\\d{4}-\\d{2}-\\d{2}$/), construct: (data) => new Date(data), instanceOf: Date, represent: (date) => date.toISOString().split('T')[0]});
// Create a schema with the custom typeconst CUSTOM_SCHEMA = yaml.DEFAULT_SCHEMA.extend([DateType]);
const yamlString = `event: !date 2025-12-31name: "New Year Party"`;
const data = yaml.load(yamlString, { schema: CUSTOM_SCHEMA });console.log(data.event instanceof Date); // trueconsole.log(data.event.getFullYear()); // 2025The yaml Library
yaml is a more modern library that offers streaming parsing and better Unicode support. It also implements the YAML 1.2 specification.
Basic Parsing
const YAML = require('yaml');
const doc = YAML.parse(`person: name: Ivan age: 30 hobbies: - programming - reading`);
console.log(doc.person.name); // "Ivan"console.log(doc.person.hobbies[0]); // "programming"