Working with YAML in JavaScript (Node.js): complete guide
YAML (YAML Ain't Markup Language) is a human-readable data serialization format widely used for configuration files, API descriptions, CI/CD pipelines, and data exchange. In the Node.js ecosystem, there are several powerful libraries for working with YAML. In this article, we will thoroughly examine the main tools, their capabilities, and usage examples.
Popular libraries for YAML in Node.js
The most common libraries for working with YAML in the Node.js environment:
- js-yaml — the most popular and actively maintained library. Supports a full range of operations: parsing, serialization, custom schemas and types.
- yaml (yaml package) — a modern alternative with support for strict parsing, comments, and AST (abstract syntax tree).
- yamljs — a lightweight library with a simple API, suitable for basic tasks.
Installing the js-yaml library
To start working with YAML in Node.js, install the library via npm:
npm install js-yamlAfter installation, import the library into your project:
const yaml = require('js-yaml');const fs = require('fs');Parsing YAML into a JavaScript object
The main operation is converting a YAML string into a JavaScript object:
const yamlString = `server: host: localhost port: 8080 ssl: truedatabases: - name: users type: postgres - name: logs type: mongodb`;
try { const data = yaml.load(yamlString); console.log(data.server.host); // "localhost" console.log(data.databases[0].name); // "users"} catch (e) { console.error('YAML parsing error:', e.message);}The yaml.load() method safely converts a YAML string into an object. To load from a file, use:
try { const config = yaml.load(fs.readFileSync('config.yaml', 'utf8')); console.log(config);} catch (e) { console.error('Error reading configuration:', e);}Serializing a JavaScript object to YAML
The reverse operation is converting an object into a YAML string:
const configObject = { app: { name: "MyApp", version: "1.0.0" }, features: ["auth", "logging", "analytics"], database: { host: "db.example.com", port: 5432 }};
const yamlString = yaml.dump(configObject, { indent: 2, lineWidth: 120, noRefs: true});
console.log(yamlString);// Output:// app:// name: MyApp// version: 1.0.0// features:// - auth// - logging// - analytics// database:// host: db.example.com// port: 5432Parameters of the yaml.dump() method:
indent— number of spaces for indentation (default 2)lineWidth— maximum line length (default 80)noRefs— disable the use of anchors and referencesskipInvalid— skip invalid values instead of throwing an error
Working with custom YAML types
js-yaml supports custom schemas and data types. For example, you can add support for dates:
const yaml = require('js-yaml');
// Creating a custom schema with date supportconst schema = yaml.DEFAULT_SCHEMA.extend([ new yaml.Type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: (data) => { return !isNaN(Date.parse(data)); }, construct: (data) => { return new Date(data); }, instanceOf: Date, represent: (date) => { return date.toISOString(); } })]);
const yamlString = 'event_date: 2024-03-15T14:30:00Z';const parsed = yaml.load(yamlString, { schema });console.log(parsed.event_date inst